Kevin Tse - 1 year ago 121
Python Question

# List length check not working in Sudoku checker

I want to write some Python code to check that whether a matrix accords with the rule of Sudoku. My code is presented below:

``````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
``````

But here's a weird problem in the if statement. After the two inner while loops, the statement "len(checked)" evaluates to 0 which should not be like that. I don't know what happened.

Answer Source

The problem is you're not initializing `j` properly for the two inner while loops. Here's your code and the indicated modifications to make it work:

``````def check_sudoku(matrix):
n = len(matrix)
# check each row
#    i, j = 0, 0
i = 0
while i < n:
j = 0  # added
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
i = 0
while i < n:
j = 0  # added
checked = []
while j < n:
if matrix[j][i] not in checked:
checked.append(matrix[j][i])
j += 1
if len(checked) < n:
return False
i += 1

return True
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download