Variable changing in unexpected way Python

47 Views Asked by At

I am trying to make a function that will keep trying different numbers in a cell of a board made with a 2D list until its constraints are met. However, for some reason when I output the row and column that is being tested, it works normally until it suddenly goes back an entire row with a column index out of range.

def sudoku_solver(row=None, col=None):
    if row is None:
        row = 0

    if col is None:
        col = 0

    global board
    if col >= len(board) - 1:
        sudoku_solver(row=row + 1)

    if row >= len(board) - 1:
        display_board()
        exit()

    print(row, col)
    for n in range(1, 10):
        if valid(n, row, col):
            board[row][col] = n
            sudoku_solver(row, col=col + 1)
        elif board[row][col] != 0:
            sudoku_solver(row, col=col + 1)
        else:
            pass # board[row][col] = 0

    return False

Output:

....(a lot of tests)

5 3

5 4

5 4

5 4

5 4

5 4

5 4

4 9

This is the board:

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

There are 0 best solutions below