我無法圍繞爲什麼我的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。不要讓吸氣者和安裝者。 –