2015-03-02 2 views
0

Вот код, который я использую, и получение объекта 'int' не является итерируемой ошибкой, и Idon't не знает, как исправить это.Ближайший сосед - код ошибки iterable в 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

+1

Каким образом '[0,8,7,5,2,10]' график? Как связаны эти целые числа? Где края? Как вы можете определить соседей от этого? –

+0

Возможно, это потому, что вы не написали его соседом. – Moberg

ответ

0

Поскольку у вас есть graph=[0,8,7,5,2,10], graph[start] является целым числом, следовательно, вы получили ошибку в для цикла:

for neighbor in graph[start]: 

, и я не думаю, что вы можете использовать graph[start][neighbor] в строке: tentativedist = distances[start] + graph[start][neighbor]

Смежные вопросы