最近邻 - 在Python中可迭代的错误代码

时间:2015-03-02 13:01:57

标签: python nearest-neighbor

以下是我使用和获取' int'的代码。对象不是可迭代的错误,并且我不知道如何修复它。

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)

1 个答案:

答案 0 :(得分: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]

相关问题