I need to check if the number the user insert is already in the colum, row or “block” (still working on the last part).
for some reason these checks don’t work and I don’t get why?
I wrote the same code in the shell and it worked just fine.
my code:
def is_valid_move(board,row, column, digit):
if digit in board[row]:
print "Row already contains", digit
return (False)
else:
return (True)
for i in range(9):
if digit in board[i][row]:
print "Colum already contains", digit
return (False)
break
else:
return (True)
board = [[3,7,0,0,5,0,0,0,0],
[0,6,0,0,3,0,2,0,0],
[0,2,9,4,0,0,0,7,8],
[0,0,4,1,7,0,0,8,0],
[0,0,6,3,0,5,9,0,0],
[0,5,0,0,8,4,1,0,0],
[7,1,0,0,0,8,5,6,0],
[0,0,5,0,1,0,0,2,0],
[0,0,0,0,9,0,0,1,3]]
a=is_valid_move(board,1, 2, 9)
print a
output I get:
True
any idea how to check if number is already in the box?
Thanks!
The problem is that you return true, as soon as you find any check that does not fail. So if you have a valid row, your check is already successful, although the column could be full with the same number.
So basically, remove all
return Truelines and put a single one at the very end after all checks are over.Also a few more things:
TrueorFalsein your returns.breakafterreturnas the latter will already end the function.board[i][row]evaluates in a single digit, so a check withdigit inwill not work as it expects an iterable.board[i][row]should beboard[i][column]as the first list index is already the row.To check if the third condition for a 3×3 group is valid, you first need to identify which “box” a cell belongs to, and then check all the numbers inside: