问题
I have a networkx graph in Python, with weighted edges. I want to get the weight of the smallest path between two nodes.
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?
回答1:
You look for single_source_dijkstra:
from networkx.algorithms.shortest_paths.weighted import single_source_dijkstra
single_source_dijkstra(G,s,t)
example
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')
output
(1.9, ['b', 'a', 'd', 'c', 'f'])
回答2:
The networkx documentation has this page: shortest paths.
There are several options, but it looks like shortest_path_length()
is what you want.
For clarity:
shortest_path = nx.shortest_path_length(G, source, destination, 'distance')
来源:https://stackoverflow.com/questions/56308298/how-to-get-the-weight-of-the-smallest-path-between-two-nodes