【发布时间】:2019-05-25 20:05:05
【问题描述】:
我在 Python 中有一个带有加权边的 networkx 图。我想得到两个节点之间最小路径的权重。
目前,我正在从 nx.shortest_path 实现中获取最短路径中的节点,然后遍历每对节点并对每对节点之间的权重求和。
shortest_path = nx.shortest_path(G, source, destination, 'distance')
#function to iterate over each pair
import itertools
def pairwise(iterable):
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
weightSum = 0
for adjPair in pairwise(shortest_path):
weightSum = weightSum + G[adjPair[0]][adjPair[1]]['distance']
有没有更好的(内置)替代方案?
【问题讨论】:
-
最小路径是什么意思?边数最少的路径?权重最低的路径?
-
我认为使用 Djikstra 的最短路径给出了权重最小的路径。我想知道那个重量。
标签: python python-3.x networkx shortest-path dijkstra