Networkx - Shortest Path Length

I use networkx to manage a large network, which consists of 50k nodes.

I want to calculate the shortest path length between a specific set of nodes, for example N.
For this, I use the nx.shortest_path_length function.

There may be no way in some nodes from N, so networkx raises and stops my program.

Is there a way to run this program without errors?
And tell shortest_path_length to return some maximum value?

The code just uses nx.shortest_path_length(G,i,j) in a loop. and the error is as follows

raise nx.NetworkXNoPath("No path between %s and %s." % (source, target)) networkx.exception.NetworkXNoPath: No path between V and J

+8
source share
2 answers
 import networkx as nx G=nx.Graph() G.add_nodes_from([1,2,3,4]) G.add_edge(1,2) G.add_edge(3,4) try: n=nx.shortest_path_length(G,1,4) print n except nx.NetworkXNoPath: print 'No path' 
+14
source

Alternatively, depending on the type of graph, namely directed , strongly or loosely coupled or non-oriented --create component subgraphs (sub_G), i.e.

(G.subgraph(c) for c in connected_components(G))

or if indicated:

nx.weakly_connected_component_subgraphs(G) or nx.strongly_connected_component_subgraphs(G)

In addition, given that sub_G is a directed graph, check the strength of its connections, for example

nx.is_strongly_connected(sub_G) or ng.is_weakly_connected(sub_G)

In combination or individually, these recommendations will reduce unnecessary verification of paths that do not exist due to the nature of the subgraph (s) of the component.

0
source

Source: https://habr.com/ru/post/909268/


All Articles