I'm working on a Sudoku solver (for a Leet problem) and I'm able to manipulate the 9 x 9 array of numbers in terms of rows and columns pretty easily using basic indexing, e.g.,
board[row,:]
or board[:,col]
. Each of these slices a 1D array from the 2D array.
I'd like to do the equivalent for the 3 x 3 subblocks of a Sudoku board, in the following sense. I'd like to define a Python function iBlock
that takes as argument the block row and block column numbers, and returns something such that board[something]
addresses the 9 elements of a subblock such that board[something]
could be used as follows:
board[something] = [ 3, 7, 2, 1, 4, 5, 9, 8, 6 ]
would have the effect of transforming the full 9 x 9 board from
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . - - - . . .
. . . - - - . . .
. . . - - - . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
to:
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . 3 7 2 . . .
. . . 1 4 5 . . .
. . . 9 8 6 . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
and I'd like to be able to use board[something]
on the rhs of an assignment as well.
So the question is... what is something so that things would work as above?
Hopfully this information helps. I would use numpy and slicing.
Here is a small example that hopefully produces your desired results:
import numpy as np
mat = np.zeros((9,9))
start = 3
end = 6
mat[start:end,start:end] = np.array([ 3, 7, 2, 1, 4, 5, 9, 8, 6 ]).reshape((3,3))
print(mat)
[[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 3. 7. 2. 0. 0. 0.]
[0. 0. 0. 1. 4. 5. 0. 0. 0.]
[0. 0. 0. 9. 8. 6. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]]