coolhill coolhill - 14 days ago 6
Python Question

Python prints different value each iteration but value is not changed.

I cannot wrap my head around why my python code acts in a certain way.

Since I do not change "current" the output should be the same for each iteration? This is a problem because I need "current" to be the same so each Node is generated from the same start-value.

See the following code:

tester.py

class Node:
def __init__(self, board=None):
self.board = board

def getBoard(self):
return self.board

def swap(self, xPos, yPos): # swap with zero

for a in self.board:
if 0 in a:
self.board[self.board.index(a)][a.index(0)] = self.board[xPos][yPos]

self.board[xPos][yPos] = 0

open = []

def gen_nodes(current):

for i in [7, 15, 11]:

print(current) # <-- why does this print a different value each time?

new = Node(current)

for a in new.getBoard():
if i in a:
xPos = new.getBoard().index(a)
yPos = a.index(i)

new.swap(xPos, yPos)

open.append(new)

if __name__ == '__main__':
gen_nodes([[1, 2, 3, 4],
[8, 5, 6, 7],
[9, 10, 11, 0],
[12, 13, 14, 15]])


Output:

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

Answer

the problem is, that you save a reference to the array in current inside the board variable in Node. This way, when you call swap, this array is changed. Instead, you probably want a new copy of the array in every node, you can use copy.deepcopy(node) for that.

Comments