最近邻-Python中的错误代码iterable
这是我正在使用的代码,得到的“int”对象是不可编辑的错误,我不知道如何修复它最近邻-Python中的错误代码iterable,python,nearest-neighbor,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 distan
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)
def shortestpath(图形、开始、结束、访问=[],距离={},前置={}):
“”“查找列表起点和终点之间的最短路径”“”
#检测是否是第一次通过,将当前距离设置为零
如果未访问:距离[开始]=0
如果开始=结束:
#我们已经找到了终点,现在找到通往终点的道路,然后返回
路径=[]
当结束时!=无:
path.append(结束)
end=precements.get(end,None)
返回距离[开始],路径[:-1]
#根据算法处理邻居,跟踪前辈
对于图[start]中的邻居:
如果邻居未被访问:
neighbordist=距离.get(neighbor,sys.maxint)
TentiveDist=距离[开始]+图形[开始][邻居]
返回触控者
如果TentiveDist
由于您有图形=[0,8,7,5,2,10]
,图形[start]
是一个整数,因此在for循环中出现错误:
for neighbor in graph[start]:
而且我不认为你可以使用
graph[start][neighbor]
作为一行:tentivedist=distance[start]+graph[start][neighbor]
你可以编辑你的帖子来包含完整的回溯错误,而不是你的信息摘要吗?[0,8,7,5,2,10]
是一个什么样的图形?这些整数是如何连接的?边缘在哪里?你怎么能从中判断邻居呢?也许是因为你没有拼写邻居。