NetworkX

Previous topic

networkx.algorithms.shortest_paths.generic.shortest_path_length

Next topic

networkx.algorithms.shortest_paths.unweighted.single_source_shortest_path

networkx.algorithms.shortest_paths.generic.average_shortest_path_length

networkx.algorithms.shortest_paths.generic.average_shortest_path_length(G, weighted=False)

Return the average shortest path length.

The average shortest path length is

a =\sum_{s,t \in V} \frac{d(s, t)}{n(n-1)}

where V is the set of nodes in G, d(s, t) is the shortest path from s to t, and n is the number of nodes in G.

Parameters :

G : NetworkX graph

weighted : bool, optional, default=False

If True use edge weights on path.

Raises :

NetworkXError: :

if the graph is not connected.

Notes

If weighted=True and the graph has no ‘weight’ edge attribute the value 1 will be used.

Examples

>>> G=nx.path_graph(5)
>>> print(nx.average_shortest_path_length(G))
2.0

For disconnected graphs you can compute the average shortest path length for each component: >>> G=nx.Graph([(1,2),(3,4)]) >>> for g in nx.connected_component_subgraphs(G): ... print(nx.average_shortest_path_length(g)) 1.0 1.0