本文介绍了如何获得两个节点之间最小路径的权重?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Python中有一个带有加权边的networkx图。我想获得两个节点之间最小路径的权重。
I have a networkx graph in Python, with weighted edges. I want to get the weight of the smallest path between two nodes.
当前,我正在从nx.shortest_path实现中获得最短路径中的节点,然后遍历每对节点并
Currently, I am getting the nodes in the shortest path from the nx.shortest_path implementation, and then iterating through each pair and summing over the weights between each pair of node.
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']
是否有更好的(内置)替代方法
Is there a better (built-in) alternative to this?
推荐答案
您在寻找:
from networkx.algorithms.shortest_paths.weighted import single_source_dijkstra
single_source_dijkstra(G,s,t)
示例
import networkx as nx
from networkx.algorithms.shortest_paths.weighted import single_source_dijkstra
G = nx.Graph()
G.add_edge('a', 'b', weight=0.6)
G.add_edge('a', 'c', weight=6)
G.add_edge('c', 'd', weight=0.1)
G.add_edge('c', 'e', weight=0.7)
G.add_edge('c', 'f', weight=0.9)
G.add_edge('a', 'd', weight=0.3)
single_source_dijkstra(G,'b','f')
输出
(1.9, ['b', 'a', 'd', 'c', 'f'])
这篇关于如何获得两个节点之间最小路径的权重?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!