nx.shortest_path w/ weight

70 views
Skip to first unread message

ilter yüksel

unread,
Nov 23, 2023, 12:43:25 PM11/23/23
to networkx...@googlegroups.com
Hi all,

I'd like to calculate the shortest path according to edge weight but couldn't succeed. Could you please explain what I miss here?

As far as I know. weight of the edges w/out weight value should be considered as 1. The shortest path should be [0, 1, 2, 3, 4] since the weight of edge 1-5 is assigned as 50. 

import networkx as nx

G = nx.path_graph(5)
G.add_node(5)
print(nx.shortest_path(G, source=0, target=4))
G.add_edge(1,5)
G.add_edge(5,4, weight=50)
print(nx.shortest_path(G,0,4))
print(G.edges.data())

Output;

[0, 1, 2, 3, 4]
[0, 1, 5, 4]
[(0, 1, {}), (1, 2, {}), (1, 5, {}), (2, 3, {}), (3, 4, {}), (4, 5, {'weight': 50})]

Thanks,
İlter

Ross Barnowski

unread,
Nov 30, 2023, 5:58:23 PM11/30/23
to networkx-discuss
According to the [shorest_path docstring](http://networkx.org/documentation/latest/reference/algorithms/generated/networkx.algorithms.shortest_paths.generic.shortest_path.html), the default value for the `weight` attribute is `weight=None`, meaning that edge weight attributes are not considered in the calculation. In order to get the weighted calculation, you must explicitly specify the edge attribute name containing the weights, e.g. `nx.shortest_path(G, source=0, target=4, weight="weight")`

Hope that helps!

ilter yüksel

unread,
Dec 3, 2023, 3:11:13 AM12/3/23
to networkx...@googlegroups.com
Thanks Ross, it works! 

--
You received this message because you are subscribed to the Google Groups "networkx-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to networkx-discu...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/networkx-discuss/148b3608-f617-49da-90e4-5a8ffe4c5ebcn%40googlegroups.com.


--
--ilter
Reply all
Reply to author
Forward
0 new messages