Search code examples
pythonpython-3.xsudoku

Iterate through sudoku subgrid to check for specific value


Im trying to create a function that given a sudoku board, row, column and value, it iterates through the subgrid to which the row and column belongs to and checks if the value is in that subgrid. I have already made the function that identifies to which subgrid the row and column belongs. Im stuck with the function that checks if the value is in that subgrid. Eg:

check_subgrid(       (3, 9, 1), (2, 3, 5, 8, 6), (6, 1, 4),
                     (8, 7, 6), (1, 2, 7, 8),    (9, 8, 2),
                     (2, 8, 5), (6, 9, 2, 3, 1), (5, 9, 3)
                     ), 0, 1, 9)

This should iterate through: (3,9,1), (8,7,6) and (2,8,5). The output should return True, since 9 in that subgrid, otherwise False. So far the code I have is the following:

def check_subgrid(sudoku, row, column, value)
    x_origin, y_origin = get_subgrid_origin(row, column)
        for x in str(x_origin):
            for y in str(y_origin):
                for i in range(3):
                 #here I should iterate through every subgrid row looking for the value entered.

I hope I explained my self, if you have any doubt do not hesitate to ask.


Solution

  • [too long for a comment]

    Understanding what you have so far would be easier with a bit more of your code and data structures. Commonly (but definitely not always), a sudoku board is set up as list of rows, each of which is a list of numbers, zeroes representing blanks:

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

    This allows you find where everything is on the grid, which at the moment I don't think you can do - you have not correctly recorded the position of the entries in the grid (because you don't record the blanks). If this is not how you are storing your data, or even if it is, you should explain that.

    In your sample code, you have the strange for x in str(x_origin): which iterates x through the characters of the text representation of x_origin. This seems entirely wrong; more likely is that you want something like for x in range(x_origin,x_origin+3)