Home > front end >  Python: why does this variable value change?
Python: why does this variable value change?

Time:01-04

I am learning recursion and came through this code (not mine: https://github.com/kying18/sudoku) and cannot figure out why the variable example_board changes value. It is never addressed again and no other variable is linked to it? I tested it and it does!

Here is the condensed version of the relevant code:

def find_next_empty(puzzle):
    #returns a row, col for a empty square

def is_valid(puzzle, guess, row, col):
    #checks if guess is True or False

def solve_sudoku(puzzle):
    row, col = find_next_empty(puzzle)

    if row is None:  # this is true if our find_next_empty function returns None, None
        return True 
    
    for guess in range(1, 10): # range(1, 10) is 1, 2, 3, ... 9
        if is_valid(puzzle, guess, row, col):
            puzzle[row][col] = guess
            if solve_sudoku(puzzle):
                return True
        
        puzzle[row][col] = -1

    return False

if __name__ == '__main__':
    example_board = [
        [3, 9, -1,   -1, 5, -1,   -1, -1, -1],
        [-1, -1, -1,   2, -1, -1,   -1, -1, 5],
        [-1, -1, -1,   7, 1, 9,   -1, 8, -1],

        [-1, 5, -1,   -1, 6, 8,   -1, -1, -1],
        [2, -1, 6,   -1, -1, 3,   -1, -1, -1],
        [-1, -1, -1,   -1, -1, -1,   -1, -1, 4],

        [5, -1, -1,   -1, -1, -1,   -1, -1, -1],
        [6, 7, -1,   1, -1, 5,   -1, 4, -1],
        [1, -1, 9,   -1, -1, -1,   2, -1, -1]
    ]
    print(solve_sudoku(example_board))
    print(example_board)
'''

CodePudding user response:

Before you dive into the implementatino details you must understand what passing parameter by reference or by value means, because python passes by reference:

Pass means to provide an argument to a function. By reference means that the argument you’re passing to the function is a reference to a variable that already exists in memory rather than an independent copy of that variable.

Since you’re giving the function a reference to an existing variable, all operations performed on this reference will directly affect the variable to which it refers. Let’s look at some examples of how this works in practice.

Reference this article

CodePudding user response:

When printing in the line: "print(solve_sudoku(example_board))" example_board is passed into solve_sodoku. The solve_sodoku function then changes it values in this line: "puzzle[row][col] = guess" as puzzle is referencing the example_board variable and one of its value is being changed to guess.

Hope this helped!

  •  Tags:  
  • Related