I would like to extract a very specific portion of a 2D array in Python using the zip()
method (and avoid messy for loop logic). I'd like to use zip to achieve something like this:
>>> sub_matrix = list(zip([*grid[0:3]]*3))
# Desired output example (Option 1)
[".","4",".", ".",".","4",".",".","."]
# Desired output example (Option 2)
[[".","4","."],
[".",".","4"],
[".",".","."]]
I am working with the 2D array below in Python on an interview practice problem.
grid = [[".","4",".",".",".",".",".",".","."],
[".",".","4",".",".",".",".",".","."],
[".",".",".","1",".",".","7",".","."],
[".",".",".",".",".",".",".",".","."],
[".",".",".","3",".",".",".","6","."],
[".",".",".",".",".","6",".","9","."],
[".",".",".",".","1",".",".",".","."],
[".",".",".",".",".",".","2",".","."],
[".",".",".","8",".",".",".",".","."]]
Part of solving the problem involves ensuring each 3 x 3 "region" in a sudoku game contains legal values. I'd like to use zip()
to quickly extract a 3 x 3 portion of the matrix. For example, the top-left region would cause the tests to fail because it contains 4 twice.
I know I can subset the grid to get the first three rows as follows:
>>> sub_grid = grid[0:3]
>>> print(sub_grid)
[['.', '4', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '4', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '1', '.', '.', '7', '.', '.']]
I modified the printing a little bit to make it obvious, but at this point, I'd like to zip the three arrays using a 'step' of 3, so that each new array will zip 3 values from each array before moving on to the next one.
In the Python3 docs on zip
there is an excerpt on how I think this can be done, but I cannot get the desired output.
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using
zip(*[iter(s)]*n)
.
(For posterity, question is from CodeFights will be hidden until unlocked)
Any help is greatly appreciated. Thanks.
No zip but
[row[:3] for row in grid[:3]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With