我无法围绕为什么我的Python代码以某种方式行事。Python每次迭代打印不同的值,但值不会更改。
既然我不改变“当前”的输出应该是每次迭代相同?这是一个问题,因为我需要“当前”是相同的,所以每个节点都是从相同的起始值生成的。
请看下面的代码:
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]])
输出:
[[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]]
根据我刚刚提出的快速调试会话,问题出现在'new.swap(xPos,yPos)'中。我的意思是,这是'current'变化的地方。仍然试图找出究竟发生了什么.. – noamgot
'def getBoard(self):'这不是Java。不要让吸气者和安装者。 –