2016-12-31 40 views
0

我試圖做一個「路徑查找器」路徑查找器的代碼,__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__' 

可能有人請幫助我得到這個東西運行

+0

你應該避免初始化具有可變值的參數,如「list」。請參閱Python入門指南中的[Common Gotchas](http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments)! –

+0

使用'print()'來檢查你在'graph'中有什麼 - 看起來你分配了單個數字而不是列表或目錄。 – furas

+0

遞歸調用是錯誤的:傳遞的參數不尊重參數。替換爲:'newpaths = find_all_paths(節點,結束,圖形,路徑)'。 –

回答

2

有一些尷尬和錯誤:

而是與列表初始化的路徑參數,使用None。 並在函數體中創建空列表。

def find_all_paths(start, end, graph, path=None): 
    path = path or [] 

傳遞給find_all_paths的值不考慮簽名。代替 寫:

newpaths = find_all_paths(node, end, graph, path) 

由於值是整數,該圖形必須包含int代替strings

graph = {1: [2], 2: [3, 4, 5], 3: [4], 4: [5, 6], 5: [], 6: []} 

這裏是你的代碼的固定版本:

def find_all_paths(start, end, graph, path=None): 
    path = path or [] 
    path.append(start) 
    if start == end: 
     return [path] 
    paths = [] 
    for node in graph[start]: 
     if node not in path: 
      newpaths = find_all_paths(node, end, graph, path) 
      for newpath in newpaths: 
       paths.append(newpath) 
    return paths 

如果你試試這個:

graph = {1: [2], 2: [3, 4, 5], 3: [4], 4: [5, 6], 5: [], 6: []} 
print(find_all_paths(2, 5, graph)) 

您將獲得:

[[2, 3, 4, 5, 6]] 
+1

不幸的是,使用'path.append(start)'代替'path = path + [start]'會破壞算法,因爲它修改了調用者的路徑副本。如果這個改變被恢復了,它會匹配海報的「正確」答案('[[2,3,4,5],[2,4,5],[2,5]]')。 –

+0

偉大的代碼毫無疑問,但不是我正在尋找的路徑,因爲我早些時候說過我希望它是像path = [[2,5],[2,3,4,5] [2,4,5] ] 它應該顯示你的所有可用路徑 [[2,3,4,5,6]],但是6與組 – Enigma

+0

@Enigma沒有關係。好吧,由你來實現正確的算法...... –