[英]What's the difference between these codes? Why do they have different outputs?
[英]what's the difference between these 2 python codes? why different results?
我正在編寫如下的dfs代碼:
def dfs(self, graph, node, path):
if node==len(graph)-1:
self.res.append(path)
else:
for i in graph[node]:
path.append(i)
self.dfs(graph, i, path)
print(path.pop())
但是得到了不希望的結果,而我將dfs中的for循環代碼更改為:
self.dfs(graph, i, path+[i])
結果就是我想要的。 但是我不知道這兩個代碼有什么區別。 謝謝
在算法方面,我需要有關如何表示圖形的更多信息,以提供更多見解。 但是在代碼方面,差異是由於Python中的List是可變的這一事實引起的。 這意味着在您的原始代碼中,當您pop
path
列表時, res
的條目將相應更改。 通過以下檢查。
a = [1,2,3]
b = []
b.append(a) # b = [[1,2,3]]
a.pop() # now b = [[1,2]]
但是,當您將參數更改為path + [i]
,將構造一個新的List,即,下一個dfs
遞歸調用中的path
與上一個中的path
解耦。 通過以下檢查。
a = [1,2]
b = []
b.append(a+[3]) # b = [[1,2,3]]
a.pop()
# b is still [[1,2,3]], because the expression a + [3] will be evaluated to another List
原始版本會在每次遞歸的每次迭代中更改路徑。 第二個版本只是復制並添加了一個額外的元素。 此副本未綁定到名稱,它只是傳遞到下一級遞歸。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.