I\'m using the networkx
package in Python 2.7 Enthought distribution
to calculate shortest paths between a network of seaports. It\'s working fine
Experimenting a bit, it appears that nx.dijkstra_path
raises a misleading exception when the origin and destination nodes are the same:
>>> import networkx as nx
>>> g = nx.Graph()
>>> g.add_edge('a', 'b', distance=0.3)
>>> g.add_edge('a', 'c', distance=0.7)
>>> nx.dijkstra_path_length(g, 'b', 'c', 'distance')
1.0
>>> nx.dijkstra_path(g, 'b', 'c', 'distance')
['b', 'a', 'c']
>>> nx.dijkstra_path_length(g, 'b', 'b', 'distance')
0
>>> nx.dijkstra_path(g, 'b', 'b', 'distance')
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
nx.dijkstra_path(g, 'b', 'b', 'distance')
File "C:\Users\barberm\AppData\Roaming\Python\Python27\site-packages\networkx\algorithms\shortest_paths\weighted.py", line 74, in dijkstra_path
return path[target]
TypeError: list indices must be integers, not str
So just make an explicit test whether destination
and origin
are the same, and handle it separately when they are.