Search code examples
pythoniterationnetworkxsubgraph

Python networkx iterating through list of subgraphs


I am having a bit of trouble obtaining an iteration through all possible subragphs of a large nx graph G, taken as input from a text file.

The following is some code I found on StackOverflow, but is not yielding what i am looking for:

    g = read_graph(sys.argv[1])

    print ('Number of subgraphs:', len(g.subgraph(g.nodes())))

    # extract subgraphs
    sub_graphs = nx.connected_component_subgraphs(g)

    for i, sg in enumerate(sub_graphs):
        print "subgraph {} has {} nodes".format(i, sg.number_of_nodes())
        print "\tNodes:", sg.nodes(data=True)
        print "\tEdges:", sg.edges() 

Prints out:

('Number of subgraphs:', 4039)
subgraph 0 has 4039 nodes
    Nodes: <generator object nodes at 0x10ed77910>
    Edges: <generator object edges at 0x10ed77910>

What I am trying to do is be able to iterate through all possible subgraphs of length 3 or greater, then perform certain functions on them as graphs.

Thanks!


Solution

  • I'm writing this under the assumption that "length 3" means "at least 3 nodes".

    import networkx as nx
    g = read_graph(sys.argv[1])
    
    for subgraph in nx.connected_component_subgraphs(g):
        if subgraph.number_of_nodes()>2:
             #your code here