Reputation: 245
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!
Upvotes: 4
Views: 1094
Reputation: 387607
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 True
lines and put a single one at the very end after all checks are over.
Also a few more things:
True
or False
in your returns.break
after return
as the latter will already end the function.board[i][row]
evaluates in a single digit, so a check with digit in
will not work as it expects an iterable.board[i][row]
should be board[i][column]
as the first list index is already the row.To check if the third condition for a 3x3 group is valid, you first need to identify which “box” a cell belongs to, and then check all the numbers inside:
# get the first row/column index of a block
blockRow = row // 3 * 3
blockColumn = column // 3 * 3
# check all 8 fields in the block
for r in range(blockRow, blockRow + 3):
for c in range(blockColumn, blockColumn + 3):
# skip the field we want to check
if r == row and c == column:
continue
if digit == board[r][c]:
return False
Upvotes: 5
Reputation: 33
if you want to create a sudoku for the users take this tips the way to remove the numbers its in mirror mode (sorry for my english) example
(1 _ 3 4)
(7 _ 5 6)
Upvotes: 0