Home > Blockchain >  How to remove loops from three nodes? [networkx]
How to remove loops from three nodes? [networkx]

Time:02-23

I have a graph with hundreds of edges and I want to remove loops like this:

(1, 2)
(1, 3)
(2, 3)

I have tried:

G.remove_edges_from(nx.selfloop_edges(G)) 

But it does not seems to work. Any advices?

CodePudding user response:

Selfloops are edges of a node to itself. For example, (1,1) or (2,2) are self loops. The example you is a simple cycle, i.e., a closed path were no node appears twice. You can use simple_cycle or find_cycle. For example, you could iteratively use find cycle:

import networkx as nx

G = nx.karate_club_graph()
print(nx.find_cycle(G, orientation="ignore"))
# [(0, 1, 'forward'), (1, 2, 'forward'), (2, 0, 'forward')]
  • Related