Reputation: 1041
I have the shortest path between two nodes in a network.
I am trying to find the total cost between the two nodes.
import numpy as np
import networkx as nx
def shortest_path(a,b):
m = np.array([[0,2,1,....]])
network = nx.from_numpy_matrix(m)
path = nx.dijkstra_path(network, source=a, target=b)
ix =[[path[i],path[i+1]] for i in range(len(path)-1)]
total = sum([m[i[0]][i[1]] for i in ix])
path = nx.dijkstra_path(network, source=a, target=b)
return(total, path)
I was just wondering if there is an attribute to find the total cost variable instead of me having to code it up so that my code looks cleaner? I can't seem to find it in the docs as I am very new to networkx. Thanks in advance
Upvotes: 3
Views: 963
Reputation: 8508
You can use single_source_dijkstra
. Example usage for you (adapted from example in documentation):
total, path = nx.single_source_dijkstra(network, source=a, target=b)
Upvotes: 1