Search code examples
pythonsudokusubgrid

printing out the elements in a box in a Sudoku board


for example, I have a 9x9 sudoku board like this:

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

and I have a function: def subgrid_values(board,r,c) board takes in the size of the board which in this case is big. r takes in the row and c takes in the column.

so if I input subgrid_values(big,4,5) it will give me an output of [3,6,7,2]

a pic of the higlighted box

I'm trying to output that list but I do not know how to

I hope this makes it clearer.


Solution

  • One of the solutions would be to get the starting index of the sub-grid and loop three times on row and column as follows:

    def solution(big, r, c):
      output = []
      row_start_index = (r // 3) * 3
      col_start_index = (c // 3) * 3
    
      for ri in range(row_start_index, row_start_index + 3):
        for ci in range(col_start_index, col_start_index + 3):
          if big[ri][ci]:
            output.append(big[ri][ci])
      return output