0

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.

jedwards
30.4k3 gold badges69 silver badges94 bronze badges
asked Apr 5, 2015 at 16:10

1 Answer 1

2
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.

answered Apr 5, 2015 at 16:15
Sign up to request clarification or add additional context in comments.

1 Comment

Right, didn't know that, such a basic... g.matrix is np.matrix, so I can use np.copy(). Thanks!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.