Sudoku check conditions

I need to check if the number the user is inserting is in colum, row or "block" (still working on the last part). for some reason, these checks do not work, and I do not understand why?
I wrote the same code in the shell and it worked fine.

my code is:

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:

 True 

any idea how to check if the number is in the box?

Thanks!

+4
source share
2 answers

The problem is that you return true as soon as you find some kind of check that won't work. Therefore, if you have a valid row, your check has already been completed successfully, although the column may be filled with the same number.

So, in principle, delete all return True lines and put one of them at the very end after all the checks have been completed.

Also a few more things:

  • Do not put parentheses around True or False in your returns.
  • You do not need to break after return , since the latter will already complete this function.
  • board[i][row] is evaluated to one digit, so checking with digit in will not work, since it is waiting for iteration.
  • board[i][row] should be board[i][column] , since the first index on the list is already a row.

To check whether the third condition for the 3x3 group is really fulfilled, first you need to determine which cell the 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 
+5
source

if you want to create sudoku for users, this will tell you how to delete numbers in mirror mode (sorry for my english).

(1 _ 3 4)

  (7 _ 5 6) 
0
source

Source: https://habr.com/ru/post/1445368/


All Articles