我試圖做一個「路徑查找器」路徑查找器的代碼,__getitem__類型錯誤
def find_all_paths(start, end, graph, path=[]):
path = path + [start]
if start == end:
return [path]
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
graph={1: ['2'], 2: ['3', '4', '5'], 3: ['4'], 4: ['5', '6'], 5: [], 6: []}
,如果我在shell中輸入find_all_paths(2,5,graph)
我應該找回所有從鍵2走在圖形詞典的路徑在5個值 正確的結果應該是這樣的
path=[[2,5],[2,3,4,5][2,4,5]]
代碼一直給值錯誤,如
for node in graph[start]:
TypeError: 'int' object has no attribute '__getitem__'
可能有人請幫助我得到這個東西運行
你應該避免初始化具有可變值的參數,如「list」。請參閱Python入門指南中的[Common Gotchas](http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments)! –
使用'print()'來檢查你在'graph'中有什麼 - 看起來你分配了單個數字而不是列表或目錄。 – furas
遞歸調用是錯誤的:傳遞的參數不尊重參數。替換爲:'newpaths = find_all_paths(節點,結束,圖形,路徑)'。 –