如何在Yen的最短路径算法(python networkx)中忽略等长路径
我正在使用一个代码来实现Yen的算法,以便找到k条最短路径。但是,我希望它生成不同长度的k条最短路径,即如果多条路径具有相同的长度,它只选择其中一条并返回长度 日元算法代码如下: 我尝试将if path_uunot in A:结尾的行更改为if path_uunot in A and cost_unot in A_ucosts:,但这会返回错误如何在Yen的最短路径算法(python networkx)中忽略等长路径,python,algorithm,shortest-path,Python,Algorithm,Shortest Path,我正在使用一个代码来实现Yen的算法,以便找到k条最短路径。但是,我希望它生成不同长度的k条最短路径,即如果多条路径具有相同的长度,它只选择其中一条并返回长度 日元算法代码如下: 我尝试将if path_uunot in A:结尾的行更改为if path_uunot in A and cost_unot in A_ucosts:,但这会返回错误 AttributeError Traceback (most recent call last)
AttributeError Traceback (most recent call last)
<ipython-input-58-038c80524d5d> in <module>()
----> 1 ksp(G,'source','target',100,"weight")
<ipython-input-54-7b3d0aa42558> in ksp(graph, source, target, num_k, weight)
77 except Empty:
78 break
---> 79 except Queue.IndexError:
80 pass
81
AttributeError: 'module' object has no attribute 'IndexError'
如果我这样做
print newnewksp(G,'source','target',8,"weight")
print newksp(G,'source','target',35,"weight")
print ksp(G,'source','target',35,"weight")
其中newksp是我的建议,newnewksp@H4kim是我的建议
[12.0, 13.0, 22.0, 27.0, 31.0, 40.0, 43.0, 50.0]
[12.0, 13.0, 14.0, 15.0, 16.0, 19.0, 20.0, 21.0, 22.0, 23.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0, 34.0, 35.0, 36.0, 37.0, 39.0, 40.0, 41.0, 42.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0]
[12.0, 13.0, 13.0, 14.0, 14.0, 15.0, 15.0, 16.0, 19.0, 20.0, 20.0, 21.0, 21.0, 22.0, 22.0, 22.0, 22.0, 22.0, 23.0, 23.0, 23.0, 23.0, 24.0, 24.0, 24.0, 25.0, 25.0, 25.0, 27.0, 27.0, 28.0, 28.0, 28.0, 29.0, 29.0]
我认为您的更改是可以的,但是Queue.IndexError应该被IndexError替换,因为它是python内置的异常。相反,Empty不是内置异常,因此它应该是Queue.Empty 我想我们不应该在主循环中更改A,因为它对算法至关重要。相反,我们可以尝试通过跟踪集合中的不同成本值来改变最终条件: 将networkx导入为nx 导入队列 def path_成本图,路径,权重=无: 路径成本=0 对于rangelenpath中的i: 如果i>0: 边=路径[i-1],路径[i] 如果重量!=无: pathcost+=图形。获取边数据*边[权重] 其他: 数一数边的数目 路径成本+=1 返回路径成本 def KSPGRAPHE、源、目标、数量k、重量: 从源到目标的最短路径 A=[nx.shortest_路径图,源,目标,权重=weight] A_成本=[path_成本图,A[0],权重] 唯一成本=setA成本 初始化堆以存储可能的第k条最短路径 B=队列。优先级队列 k=1 而lenunique_成本
谢谢你的回答!如果我改为IndexError,现在会出现一个错误名称error Tracback last in-->1 kspG、'source'、'target',100、kspgraph中的权重、source、target、num_k、,权重75 A_costs.appendcost 76 break-->77除空:78除索引器外break 79:NameError:未定义全局名称“Empty”您的代码给出错误:UnboundLocalEr
ror回溯-->1 kspG,'source','target',100中最近的调用,kspgraph中的权重,source,target,num_k,weight 29 try:-->30 for i in rangelenA[k-1]-1:UnboundLocalError:赋值前引用的局部变量'k',我尝试在lenA
print newnewksp(G,'source','target',8,"weight")
print newksp(G,'source','target',35,"weight")
print ksp(G,'source','target',35,"weight")
[12.0, 13.0, 22.0, 27.0, 31.0, 40.0, 43.0, 50.0]
[12.0, 13.0, 14.0, 15.0, 16.0, 19.0, 20.0, 21.0, 22.0, 23.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0, 34.0, 35.0, 36.0, 37.0, 39.0, 40.0, 41.0, 42.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0]
[12.0, 13.0, 13.0, 14.0, 14.0, 15.0, 15.0, 16.0, 19.0, 20.0, 20.0, 21.0, 21.0, 22.0, 22.0, 22.0, 22.0, 22.0, 23.0, 23.0, 23.0, 23.0, 24.0, 24.0, 24.0, 25.0, 25.0, 25.0, 27.0, 27.0, 28.0, 28.0, 28.0, 29.0, 29.0]