简体   繁体   中英

Python: Function with matrix in argument

So, in my program I have a "main" function, which changes two elements of a given matrix. The matrix is an element of a list (in the example the list is the variable solved ) and then I want to append three new elements.

def main(matrix,direction):
    index16 = indexOf(16,matrix)
    matrix[index16[0]][index16[1]],matrix[index16[0]-1][index16[1]]=matrix[index16[0]-1][index16[1]],matrix[index16[0]][index16[1]]

    return matrix

solved = [[[2,1,3,4],
      [5,6,7,8],
      [9,10,11,12],
      [13,14,15,16]
      ]]

not_solved = [[0,"up"],
          [0,"left"]
          ]

while not_solved:
    solved.append(main(solved[not_solved[0][0]],not_solved[0][1]))
break

When I execute the program, I can see the "solved" array. However the initial matrix stays the same as in the beginning.

[[[2, 1, 3, 4], [5, 6, 7, 8], [9, 10, 11, 16], [13, 14, 15, 12]], 
 [[2, 1, 3, 4], [5, 6, 7, 8], [9, 10, 11, 16], [13, 14, 15, 12]]]

How can I repair that?

Sorry for my English. I am still learning.

you need to copy your matrix inside main so the original matrix does not change

import copy

def main(matrix,direction):
    matrixcopy = copy.deepcopy(matrix)
    index16 = indexOf(16,matrixcopy)
    matrixcopy[index16[0]][index16[1]],matrixcopy[index16[0]-1][index16[1]]=matrixcopy[index16[0]-1][index16[1]],matrixcopy[index16[0]][index16[1]]
    return matrixcopy

Returns:

[[[2, 1, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 
 [[2, 1, 3, 4], [5, 6, 7, 8], [9, 10, 11, 16], [13, 14, 15, 12]]]

The problem is your main function

def main(matrix,direction):
    index16 = indexOf(16,matrix)
    matrix[index16[0]][index16[1]],matrix[index16[0]-1][index16[1]]=matrix[index16[0]-1][index16[1]],matrix[index16[0]][index16[1]]

    return matrix

In this function you're returning matrix, but you're also changing matrix, which is your original matrix.

Consider this simple example:

>>> a=[1,2,3]
>>> def test(b):
    b[1]=4
    return b
>>> c = test(a)
>>> c
[1, 4, 3]
>>> a
[1, 4, 3]

A possible solution is to use the copy module

>>> import copy
>>> a=[1,2,3]
>>> def test(b):
    c=copy.deepcopy(b)
    c[1]=4
    return c

>>> c = test(a)
>>> c
[1, 4, 3]
>>> a
[1, 2, 3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM