Search code examples
pythonmatrixsliding-tile-puzzle

Last function code of 8puzzle in Python


def result(matrix):
        matrix2=matrix
        for a in possible_moves(matrix2):
            matrix2=matrix
            print()
            liste=swap_blank_tile(matrix2,a)
            print(liste)
            print(matrix)

I have this code in Python. Swap_blank_tile function creates a new matrix from old matrix. I want to put a value to "liste" from my first matrix. Therefore I used matrix2 in "swap_blank_tile" function, but "matrix" also is affected from "swap_blank_tile" function but i do not want it. Only matrix2 must be affected from this function. I can not solve why matrix is also affected from this function.


Solution

  • In your code when:

    matrix2=matrix
    

    matrix2 and matrix are still references to the same object, so if you change one you'll change the other. You'll probably want to create a deepcopy.

    from copy import deepcopy
    def result(matrix):
        matrix2=deepcopy(matrix)
        for a in possible_moves(matrix2):
            matrix2=deepcopy(matrix)
            print()
            liste=swap_blank_tile(matrix2,a)
            print(liste)
            print(matrix)