How to go through each sub-grid 3x3 using for loop?

799 Views Asked by At

I have been working on sudoku. The size of the original grid is 9x9 (a list containing 9 lists, each of which is a row). I need to check whether the digits only occur once per 3x3 sub-grid. In order to do that I have to go through each sub-grid using for loop (I think). So, I spent quite some time trying to do that, but I cannot seem to understand how exactly do it using for loop.

example_of_full_grid = [[5, 3, 4, 6, 7, 8, 9, 1, 2], 
           [6, 7, 2, 1, 9, 0, 3, 4, 9],
           [1, 0, 0, 3, 4, 2, 5, 6, 0],
           [8, 5, 9, 7, 6, 1, 0, 2, 0],
           [4, 2, 6, 8, 5, 3, 7, 9, 1],
           [7, 1, 3, 9, 2, 4, 8, 5, 6],
           [9, 0, 1, 5, 3, 7, 2, 1, 4],
           [2, 8, 7, 4, 1, 9, 6, 3, 5],
           [3, 0, 0, 4, 8, 1, 1, 7, 9]]
1

There are 1 best solutions below

1
On

Is it possible to use numpy for you?

The code below loops over all 9 subgrids.

import numpy as np

grid = np.array([[5, 3, 4, 6, 7, 8, 9, 1, 2], 
           [6, 7, 2, 1, 9, 0, 3, 4, 9],
           [1, 0, 0, 3, 4, 2, 5, 6, 0],
           [8, 5, 9, 7, 6, 1, 0, 2, 0],
           [4, 2, 6, 8, 5, 3, 7, 9, 1],
           [7, 1, 3, 9, 2, 4, 8, 5, 6],
           [9, 0, 1, 5, 3, 7, 2, 1, 4],
           [2, 8, 7, 4, 1, 9, 6, 3, 5],
           [3, 0, 0, 4, 8, 1, 1, 7, 9]])

for i in range(0,9,3):
    for j in range(0,9,3):
        print(grid[i:i+3,j:j+3])

This has to be changed for a list. See below:

subgrid = []
for i in range(0,9,3):
    row_3x3 = []
    for j in range(0,9):
        row_3x3.append(example_of_full_grid[j][i:i+3])
    for j in range(0,9,3):
        subgrid.append(row_3x3[j:j+3])
        print(row_3x3[j:j+3])