Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use "zip()" with a step parameter?

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.

enter image description here

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.

like image 333
Scott Skiles Avatar asked Feb 05 '23 04:02

Scott Skiles


1 Answers

No zip but [row[:3] for row in grid[:3]]

like image 183
woodpav Avatar answered Feb 06 '23 17:02

woodpav