2015-03-02 80 views
0

以下是我正在使用的代碼,並且獲取'int'對象不是可迭代錯誤,並且不知道如何解決它。最近鄰居 - 在Python中可迭代的錯誤代碼

def shortestpath(graph,start,end,visited=[],distances={},predecessors={}): 
    """Find the shortest path between start and end point of a list""" 

    # detect if it's the first time through, set current distance to zero 

    if not visited: distances[start]=0 

    if start==end: 
     # we've found our end point, now find the path to it, and return 
     path=[] 
     while end != None: 
      path.append(end) 
      end=predecessors.get(end,None) 
     return distances[start], path[::-1] 

    # process neighbors as per algorithm, keep track of predecessors 
    for neighbor in graph[start]: 
     if neighbor not in visited: 
      neighbordist = distances.get(neighbor,sys.maxint) 
      tentativedist = distances[start] + graph[start][neighbor] 
      return tentativedist 
      if tentativedist < neighbordist: 
       distances[neighbor] = tentativedist 
       predecessors[neighbor]=start 

    # neighbors processed, now mark the current point as visited 
    visited.append(start) 

    # finds the closest unvisited node to the start 
    unvisiteds = dict((k, distances.get(k,sys.maxint)) for k in graph if k not 
    in visited) 
    closest = min(unvisiteds, key=unvisiteds.get) 

    # now we can take the closest point and recurse, making it current 
    return shortestpath(graph,closest,end,visited,distances,predecessors) 



#main 
graph=[0,8,7,5,2,10] 
n=len(graph) 
start=graph[0] 
end=graph[n-1] 
print shortestpath(graph,start,end) 
+2

您是否可以編輯您的帖子以包含完整的回溯錯誤,而不是您的消息摘要? – CoryKramer 2015-03-02 13:02:43

+1

'[0,8,7,5,2,10]'是一個圖表怎麼樣?那些整數如何鏈接?邊緣在哪裏?你怎麼能根據這個來確定鄰居呢? – 2015-03-02 13:09:08

+0

也許這是因爲你沒有拼寫它的鄰居。 – Moberg 2015-03-02 13:11:41

回答

0

既然你有graph=[0,8,7,5,2,10]graph[start]是一個整數,因此您在for循環得到了錯誤:

for neighbor in graph[start]: 

,我不認爲你可以在行中使用graph[start][neighbor]tentativedist = distances[start] + graph[start][neighbor]