0

I am writing a code for girwan_newman analysis through networkx. I am having an error on line marked with $$. Its saying object of type 'generator' has no len()

# -*- coding: utf-8 -*-
"""
Created on Sun Aug 25 19:31:45 2019

@author: Manas
"""

import networkx as nx

def edge_to_remove(G):
    dict1 = nx.edge_betweenness_centrality(G) 
    list_of_tuples = dict1.items()
    list_of_tuples.sort(key= lambda x:x[1], reverse=True)
    return list_of_tuples[0][0]

def girvan(G):
    c = nx.connected_components(G) # new syntax
    for x in c:
        print(len(x))
 $$ l= len(c)
    print ("No of connected components are",l)

    while(l == 1):
        G.remove_edge(*edge_to_remove(G)) #((a,b)) -> (a,b)
        c = nx.connected_component_subgraphs(G)
        print ("No of connected components are",l)


    return c

G=nx.barbell_graph(5,0)
c=girvan(G)

for i in c:
    print (i.nodes())
    print ('..........')
user140446
  • 15
  • 6
  • 1
    I see some problems here aside from the issue you're running into. Assume it's a connected graph. Right now you're calculating `c`, finding its length. and then if it has length 1, you remove an edge, find `c` again, print that the number of components is 1 (not just `l` because you are guaranteed `l==1` to be in that loop), and then repeat this process forever because `l` never changes in the loop. Eventually once `G` has no edges you will get an error. – Joel Jan 01 '20 at 23:38

2 Answers2

0

Use list() on generator object:

l = len(list(c))
weAreStarsDust
  • 2,634
  • 3
  • 10
  • 22
  • This will give you 0. because your generator object will get exhausted. – Pygirl Jan 01 '20 at 21:17
  • @user140446 watch @Pygirl comment, she is right, so you need to use `l = len(list(c))` **befor** `for x in c:` or `l` will be zero every time. Also look @Joel [comment](https://stackoverflow.com/questions/59554856/unable-to-compute-length-of-the-generating-object/59554946?noredirect=1#comment105282259_59554856) about another problem in your code – weAreStarsDust Jan 02 '20 at 08:39
0

At this step

c = nx.connected_components(G) # new syntax
for x in c: # <---------------
    print(len(x)) 

Your c will become empty as generator object will get exhausted. You are using your generator object 'c' twice. It will become empty.

Solution1: store c as a form of list

c = list(c)

c = nx.connected_components(G) # new syntax
c = list(c)
for x in c:
    print(len(x))

Solution2:

l = 0
c = nx.connected_components(G) # new syntax
for x in c:
    print(len(x))
    l = l+1
Pygirl
  • 12,969
  • 5
  • 30
  • 43