Am writing a sudoku solver, and one piece of it is to grab the values in the 3x3 sub-box. My code below:
def taken_numbers_in_box(row, col, board):
col = col - (col % 3)
row = row - (row % 3)
print('row, col values initially are', (row, col))
taken_numbers = set()
for row in range(row, row + 3):
for col in range(col, col + 3):
print('row, col is', (row, col))
taken_numbers.add(board[row][col])
return taken_numbers
I reassign the col value to be the nearest multiple of three, then iterate over all values in the 3 by 3 box.
I know the inner for-loop assigns col to be col+1, but what I didn't expect was that, when row is incremented by 1, col would NOT reset back to its original value (i.e the value at col = col - (col % 3))
Here's the output for the print statement in the above code:
row, col values initially are (0, 0)
row, col is (0, 0)
row, col is (0, 1)
row, col is (0, 2)
row, col is (1, 2)
row, col is (1, 3)
row, col is (1, 4)
row, col is (2, 4)
row, col is (2, 5)
row, col is (2, 6)
row, col values initially are (0, 3)
row, col is (0, 3)
row, col is (0, 4)
row, col is (0, 5)
row, col is (1, 5)
row, col is (1, 6)
row, col is (1, 7)
row, col is (2, 7)
row, col is (2, 8)
row, col is (2, 9)
You'll notice that as row increments by 1, col stays at the value that the inner loop ended at. Can someone explain what's happening here? I thought Python would discard the variable local to the iteration and reset, but maybe I'm going crazy @_@
This code, on the other hand, does do what I'm looking for (but I'm surprised this is needed):
def taken_numbers_in_box(row, col, board):
col_initial = col - (col % 3)
row = row - (row % 3)
taken_numbers = set()
print('row, col values initially are', (row, col))
for row in range(row, row + 3):
col = col_initial
for col in range(col, col + 3):
print('row, col is', (row, col))
taken_numbers.add(board[row][col])
return taken_numbers
Output:
row, col values initially are (0, 2)
row, col is (0, 0)
row, col is (0, 1)
row, col is (0, 2)
row, col is (1, 0)
row, col is (1, 1)
row, col is (1, 2)
row, col is (2, 0)
row, col is (2, 1)
row, col is (2, 2)
row, col values initially are (0, 3)
row, col is (0, 3)
row, col is (0, 4)
row, col is (0, 5)
row, col is (1, 3)
row, col is (1, 4)
row, col is (1, 5)
row, col is (2, 3)
row, col is (2, 4)
row, col is (2, 5)