【发布时间】:2019-06-18 21:09:43
【问题描述】:
我正在使用 networkx 来计算 k 最短简单路径。 nx.shortest_simple_paths(G, source, target, weight=weight) 按成本升序返回路径列表(考虑权重的累积路径长度)。
我有兴趣获得这些路径的成本。 networkX中是否有任何简单的函数来获取这个?
本题与本题类似:Is there already implemented algorithm in Networkx to return paths lengths along with paths?。
我认为该帖子中发布的答案是错误的。从How to add custom function for calculating edges weights in a graph? 我提出了以下解决方案(见下文)。
这是正确的方法吗?
networkx 库中有什么简单的可用的吗?
我的目标是找出k-最短路径的成本。
G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
G.add_edge('a', 'b', weight=2)
G.add_edge('b', 'c', weight=4)
G.add_edge('a', 'c', weight=10)
G.add_edge('c', 'd', weight=6)
G.size()
def path_length(G, nodes, weight):
w = 0
for ind,nd in enumerate(nodes[1:]):
prev = nodes[ind]
w += G[prev][nd][weight]
return w
for path in nx.shortest_simple_paths(G, 'a', 'd', weight='weight'):
print(path, len(path)) # wrong approach
print(path, path_length(G,path,'weight')) # correct solution
print("--------------")
这将输出:
['a', 'b', 'c', 'd'] 4
['a', 'b', 'c', 'd'] 12
--------------
['a', 'c', 'd'] 3
['a', 'c', 'd'] 16
--------------
【问题讨论】:
标签: python python-3.x networkx shortest-path weighted-graph