Search code examples
pythongraphnetworkxtopology

Combine edges when node degree is n in networkx


I have an undirected graph as follows:

import networkx as nx
import matplotlib.pyplot as plt

l = [('1','2'),('2','3'),('3','4'),('3','5'),('1','6'),('6','7'),('6','8'),('9','8')]

G=nx.Graph()
G.add_edges_from(l)
nx.draw_networkx(G,with_labels=True)
plt.show()

enter image description here

I want to combine edges when node satisfies degree=n(like 2). I need remove node 1,2 and 8,and connect 3-6 and 6-9 in my example. So I expect the results to be as follows. enter image description here

How can I do it? Thanks in advaence


Solution

  • import networkx as nx
    import matplotlib.pyplot as plt
    
    l = [('1','2'),('2','3'),('3','4'),('3','5'),('1','6'),('6','7'),('6','8'),('9','8')]
    
    G=nx.Graph()
    G.add_edges_from(l)
    
    # Select all nodes with only 2 neighbors
    nodes_to_remove = [n for n in G.nodes if len(list(G.neighbors(n))) == 2]
    
    # For each of those nodes
    for node in nodes_to_remove:
        # We add an edge between neighbors (len == 2 so it is correct)
        G.add_edge(*G.neighbors(node))
        # And delete the node
        G.remove_node(node)
    
    nx.draw(G,with_labels=True)
    

    enter image description here