Assuming the sudoku puzzle is a 9 by 9 and is filled with 0-9. I want is 9 lists, with each list containing a 3 by 3 Sudoku box.
This is what I have:
grid = [[5, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 8, 7, 0, 6, 0],
[0, 0, 0, 0, 0, 3, 0, 0, 0],
[0, 5, 0, 0, 6, 1, 0, 7, 0],
[0, 0, 2, 0, 0, 0, 9, 0, 0],
[0, 0, 0, 4, 0, 0, 0, 0, 0],
[0, 0, 0, 5, 0, 0, 0, 4, 0],
[9, 0, 0, 0, 4, 8, 7, 0, 0],
[0, 8, 0, 3, 0, 0, 0, 0, 0]]
list1 = []
for i in range(0,3):
for j in range(0,3):
list1.append(grid[i][j])
list2 = []
for i in range(0,3):
for j in range(4,7):
list2.append(grid[i][j])
and it goes on and on.......
How do I simplify this for loop for getting a list of 3 by 3 boxes in Sudoku puzzle?
CodePudding user response:
You need to add a step
parameter to your range()
s so that you start reading in each box at the appropriate row / column index:
from itertools import product
boxes = []
for row_start, col_start in product(range(0, 9, 3), repeat=2):
boxes.append([
[grid[row][col] for col in range(col_start, col_start 3)]
for row in range(row_start, row_start 3)
])
print(boxes)
This outputs:
[
[[5, 0, 0], [0, 1, 0], [0, 0, 0]],
[[0, 0, 0], [0, 8, 7], [0, 0, 3]],
[[0, 0, 1], [0, 6, 0], [0, 0, 0]],
[[0, 5, 0], [0, 0, 2], [0, 0, 0]],
[[0, 6, 1], [0, 0, 0], [4, 0, 0]],
[[0, 7, 0], [9, 0, 0], [0, 0, 0]],
[[0, 0, 0], [9, 0, 0], [0, 8, 0]],
[[5, 0, 0], [0, 4, 8], [3, 0, 0]],
[[0, 4, 0], [7, 0, 0], [0, 0, 0]]
]
CodePudding user response:
from pprint import pprint as pp
SIZE = 3
sudoku = [[[0] * SIZE for _ in range(SIZE)] for _ in range(SIZE * SIZE)]
# example of populating it
for i in range(SIZE):
for j in range(SIZE):
counter = i * SIZE j
sudoku[counter][i][j] = counter 1
pp(sudoku)
output
[[[1, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 2, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 3], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [4, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 5, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 6], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [7, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 8, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 9]]]