running man
running man

Reputation: 1467

How to choose paths that the compute average path length is one, or two in networkx?

How to compute paths that the average path length is one, or two in networkx? For example, in this graph below, the average path length equals one is 6, and two is 2.

import networkx as nx
import matplotlib.pyplot as plt
G=nx.DiGraph()
G.add_edges_from([(1, 2), (1, 5), (1, 6), (1, 9), (2, 3), (2, 4), (6, 7)])
pos=nx.spring_layout(G, iterations=5000) 
plt.figure()
nx.draw(G, pos)

enter image description here

Upvotes: 0

Views: 146

Answers (1)

Rushabh Mehta
Rushabh Mehta

Reputation: 1559

If I understand your question correctly, you don't mean average path length, but rather simply path length in general. Your question seeks to find the paths with a given length.

Given that your graph seems to be a tree, we can name the root of the tree 'A', and then run the following code to generate the result desired:

path=nx.single_source_shortest_path(G,'A',cutoff=2)
for i in path:
    print(str(i)+" has path length "+ str(len(path[i]-1))))

Upvotes: 1

Related Questions