删除网络的内部循环

时间:2012-06-20 18:30:30

标签: python networkx

我有一个包含许多自循环的大图。我试图删除所有内部循环,以便我只留下一个大(外部)循环。有没有办法找到给定循环中的所有边?我尝试过使用graph.nodes_with_selfloops()graph.selfloop_edges,但都没有让我走得太远。

1 个答案:

答案 0 :(得分:2)

我找到了一种使用networkx.algorithms库解决这个问题的方法:

import networkx as netx
import networkx.algorithms as al

# build graph
g = netx.DiGraph()
edges = [(1,2),(2,3),(3,4),(4,1),(1,2),(2,5),(5,3),(3,4),(4,1)]
g.add_edges_from(edges)

# find cycles
cycles = al.simple_cycles(g)

# assuming that the exterior cycle will contain the most nodes
for cycle in cycles:
    print len(cycle)

结果应该是:

>>> 5

>>> 6