Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
5.7. Shortest Path Lengths
The next step is to compute the characteristic path length, , which is the average length of the shortest path between each pair of nodes. To compute it, we will start with a function provided by NetworkX, shortest_path_length. We will use it to replicate the Watts and Strogatz experiment, then we will see how it works.
Here’s a function that takes a graph and returns a list of shortest path lengths, one for each pair of nodes.
def path_lengths(G):
length_map = nx.shortest_path_length(G)
lengths = [length_map[u][v] for u, v in all_pairs(G)]
return lengths
The return value from nx.shortest_path_length
is a dictionary of dictionaries. The outer dictionary maps from each node, u
, to a dictionary that maps from each node, v
, to the length of the shortest path from u
to v
.
With the list of lengths from path_lengths
, we can compute like this:
def characteristic_path_length(G):
return np.mean(path_lengths(G))
And we can test it with a small ring lattice:
>>> lattice = make_ring_lattice(3, 2)
>>> characteristic_path_length(lattice)
1.0
In this example, all 3 nodes are connected to each other, so the mean path length is .
You have attempted
1 of
1 activities on this page