networkx.algorithms.shortest_paths.generic.average_shortest_path_length¶
-
average_shortest_path_length(G, weight=None, method='dijkstra')[source]¶ Returns 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
Vis the set of nodes inG,d(s, t)is the shortest path fromstot, andnis the number of nodes inG.Parameters: - G (NetworkX graph)
- weight (None or string, optional (default = None)) – If None, every edge has weight/distance/cost 1. If a string, use this edge attribute as the edge weight. Any edge attribute not present defaults to 1.
- method (string, optional (default = ‘dijkstra’)) – The algorithm to use to compute the path lengths.
Supported options: ‘dijkstra’, ‘bellman-ford’.
Other inputs produce a ValueError.
If
weightis None, unweighted graph methods are used, and this suggestion is ignored.
Raises: NetworkXPointlessConcept– IfGis the null graph (that is, the graph on zero nodes).NetworkXError– IfGis not connected (or not weakly connected, in the case of a directed graph).ValueError– Ifmethodis not among the supported options.
Examples
>>> G = nx.path_graph(5) >>> 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 C in nx.connected_component_subgraphs(G): ... print(nx.average_shortest_path_length(C)) 1.0 1.0