【问题标题】:How to get the weight of the smallest path between two nodes?如何获得两个节点之间最小路径的权重?
【发布时间】: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


【解决方案1】:

你找single_source_dijkstra:

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

【讨论】:

    【解决方案2】:

    networkx 文档有这个页面:shortest paths

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

    为了清楚起见:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 2016-03-04
      • 1970-01-01
      • 2021-12-18
      相关资源
      最近更新 更多