如何求两个节点之间最小路径的权重?

2024-10-02 02:35:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中有一个networkx图,带有加权边。我想得到两个节点之间最小路径的权重。在

目前,我正在从nx.最短路径实现,然后迭代每对节点并对每对节点之间的权重求和。在

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']

有没有更好的(内置的)替代方案?在


Tags: path路径networkxsource节点iterabledestinationdistance
2条回答

networkx文档有以下页面:shortest paths。在

有几个选项,但看起来shortest_path_length()就是您想要的。在

为了清楚起见:

shortest_path = nx.shortest_path_length(G, source, destination, 'distance')

你在找^{}

from networkx.algorithms.shortest_paths.weighted import single_source_dijkstra

single_source_dijkstra(G,s,t)

示例

^{pr2}$

输出

(1.9, ['b', 'a', 'd', 'c', 'f'])

相关问题 更多 >

    热门问题