CF84 CF84 - 2 years ago 127
Python Question

Python: all shortest paths in disconnected components of a graph

I am computing all the possible shortest paths between any two nodes in a regular network. If the network is connected (e.g., largest component = entire network), I have no problems.

The problem arises when I have disconnected components: given that there is no path between node

and node
, a
error is raised.

My problem: I want to skip all pairs of nodes that are not connected. I know I need an
to check for the presence of the error being raised, but I don't know how to add it to my code.

My code for computing all the possible shortest paths between any two nodes in the graph:

import networkx as nx
for n in F.nodes(): counts[n]=0
for n in F.nodes():
for j in F.nodes():
if (n!=j):
for p in gener:
for v in p: counts[v]+=1

To recap: I can use
nx.bidirectional_dijkstra(F, n, j)
to check for the existence of an edge between node
and node
, and it raises the
error if such edge is missing, but how can I check for this error so to skip a pair of non-connected nodes?

Answer Source

you can use error handling in python for this.

  nx.bidirectional_dijkstra(F, n, j)
except NetworkXNoPath:
  # do whatever you want

you can use this link for more help

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download