Python中的最近邻错误码iterable

2024-09-25 00:26:48 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我正在使用的代码,得到一个“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)

Tags: thepathingetreturnifstartgraph
1条回答
网友
1楼 · 发布于 2024-09-25 00:26:48

由于您有graph=[0,8,7,5,2,10]graph[start]是一个整数,因此在for循环中出现错误:

for neighbor in graph[start]:

我不认为你可以用graph[start][neighbor]来表达:tentativedist = distances[start] + graph[start][neighbor]

相关问题 更多 >