我想編寫一些Python代碼來檢查矩陣是否符合數獨規則。我的代碼如下:列表長度檢查在數獨檢查器中不起作用
correct = [[1,2,3],
[2,3,1],
[3,1,2]]
incorrect = [[1,2,3,4],
[2,3,1,3],
[3,1,2,3],
[4,4,4,4]]
incorrect2 = [[1,2,3,4],
[2,3,1,4],
[4,1,2,3],
[3,4,1,2]]
incorrect3 = [[1,2,3,4,5],
[2,3,1,5,6],
[4,5,2,1,3],
[3,4,5,2,1],
[5,6,4,3,2]]
incorrect4 = [['a','b','c'],
['b','c','a'],
['c','a','b']]
incorrect5 = [ [1, 1.5],
[1.5, 1]]
def check_sudoku(matrix):
n = len(matrix)
# check each row
i, j = 0, 0
while i < n:
checked = []
while j < n:
if matrix[i][j] not in checked:
checked.append(matrix[i][j])
j += 1
if len(checked) < n:
return False
i += 1
# check each column
i, j = 0, 0
while i < n:
checked = []
while j < n:
if matrix[j][i] not in checked:
len(checked)
checked.append(matrix[j][i])
j += 1
if len(checked) < n:
return False
i += 1
return True
# the output should look like this:
print(check_sudoku(incorrect))
#>>> False
print(check_sudoku(correct))
#>>> True
print(check_sudoku(incorrect2))
#>>> False
print(check_sudoku(incorrect3))
#>>> False
print(check_sudoku(incorrect4))
#>>> False
print(check_sudoku(incorrect5))
#>>> False
但是,if語句中存在一個奇怪的問題。在兩個內部while循環之後,語句「len(checked)」的計算結果爲0,不應該如此。我不知道發生了什麼事。
「後內循環」哪一個? –
內部while循環 –
您應該考慮將您的'check_sudoku'分解爲更多功能。 – PhilipB