I have got a problem that changes wrong variable in a function(s) shown below.
def no_updown() -> int:
print(g.matrix)
count = 0
arr = g.matrix
arr = g.move_elements(arr)
for x in range(g.size):
for y in range(g.size - 1):
if arr[y, x] == arr[y + 1, x] and arr[y, x] > 0:
arr[y, x] *= 2
arr[y + 1, x] = 0
count += 1
return count
And here is g.move_elements:
def move_elements(self, arr) -> np.matrix:
for x in range(self.size):
temp = 0
for y in range(self.size):
if not arr[y, x] == 0:
arr[temp, x] = arr[y, x]
if not temp == y:
arr[y, x] = 0
temp += 1
return arr
I want to operate only on arr from no_updown(). Instead what am I getting is g.matrix changed. I believe this has something to do with referencing, but I don't know quietly what.
1 Answer 1
arr = g.matrix
You have made arr and g.matrix refer to the same object. So naturally, changes made via either name are visible from the other.
I don't know what kind of object g.matrix is (although I can see it's not a Python list) but there's probably a way to copy it and avoid this problem. If it's a NumPy array, you can use numpy.copy.