1

I have a long list of sources and targets that form a graph as follows:

id_a = [...] #source nodes
id_b = [...] #target nodes
distance = [..] #distance between source and target nodes

G = nx.Graph()
path, length = [], []
for a, b, c in zip(id_a, id_b, distance):
    G.add_edge(a, b, weight=c)

cl is a subset of all the nodes in the graph and I want to extract the paths interconnecting all of cl together so I use all_simple_paths()

path = []
for i in range(len(cl)):
    for j in range(len(cl)):
        if i != j:
            path.append(nx.all_simple_paths(G, source=cl[i], target=cl[j]))

I want to be able to list all the simple paths and their lengths so I try:

for i in range(len(path)):
    total_length = 0
    for j in range(len(path[i])-1):
        source, target = path[i][j], path[i][j+1]
        edge = G[source][target]
        length = edge['weight']
        total_length += length
    length.append(total_length)

But I keep getting the error

object of type 'generator' has no len()

And I can't figure out how to convert the generator of all_simple_paths() to lists that I can iterate over and extract the full lengths of all the paths.

Any help is appreciated!

mb567
  • 691
  • 6
  • 21

1 Answers1

0

If you read the documentation of all_simple_paths, you will see that it returns a generator. So, just use extend instead of append method like this

path = []
for i in range(len(cl)):
    for j in range(len(cl)):
        if i != j:
            path.extend(nx.all_simple_paths(G, source=cl[i], target=cl[j]))

For more info on why extend works in this case, see this answer.

Also I see in the last part of your code, you are setting length as length = edge['weight'], then appending using length.append(total_length). This will return as error, since the edge weight will be an int. Use different variable names something like this

path_weight = []    #<----- List to store all path's weights
for i in range(len(path)):
    total_length = 0
    for j in range(len(path[i])-1):
        source, target = path[i][j], path[i][j+1]
        edge = G[source][target]
        length = edge['weight']          #<--- Get the weight
        total_length += length
    path_weight.append(total_length)     #Append to the list
Gambit1614
  • 8,547
  • 1
  • 25
  • 51