Warning

This documents an unmaintained version of NetworkX. Please upgrade to a maintained version and see the current NetworkX documentation.

Source code for networkx.algorithms.shortest_paths.generic

# -*- coding: utf-8 -*-
"""
Compute the shortest paths and path lengths between nodes in the graph.

These algorithms work with undirected and directed graphs.

"""
#    Aric Hagberg <hagberg@lanl.gov>
#    Dan Schult <dschult@colgate.edu>
#    Pieter Swart <swart@lanl.gov>
[docs]def average_shortest_path_length(G, weight=None): r"""Return the average shortest path length. The average shortest path length is .. math:: 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 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. Raises ------ NetworkXError: if the graph is not connected. 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 """ if G.is_directed(): if not nx.is_weakly_connected(G): raise nx.NetworkXError("Graph is not connected.") else: if not nx.is_connected(G): raise nx.NetworkXError("Graph is not connected.") avg=0.0 if weight is None: for node in G: path_length=nx.single_source_shortest_path_length(G, node) avg += sum(path_length.values()) else: for node in G: path_length=nx.single_source_dijkstra_path_length(G, node, weight=weight) avg += sum(path_length.values()) n=len(G) return avg/(n*(n-1))