在Graph中查找孤立的循环

时间:2015-12-26 18:49:05

标签: python-2.7

我需要在Graph(g)中找到隔离的循环,给出一个indegree = outdegree = 1的节点列表。

g = {1:[2], 2:[3], 3:[4,5], 6:[7], 7:[6]}
nodes = [6,7]
print findIsolatedCycles(g, nodes)
[[6, 7, 6]]

这是我的代码在上面这样的简单情况下工作正常,但是给定一个巨大的数据集它会给出错误:

ValueError: list.remove(x): x not in list 

我的代码:

def findIsolatedCycles(g, nodes):
"""Find isolated cycles given a list of one-in-one-out nodes"""
paths = []
for node in nodes:
    isolatedCycle = []
    def visit(n):
        while len(g[n]) > 0:
            nodes.remove(n)
            dst = g[n].pop()
            visit(dst)
        isolatedCycle.append(n)
    visit(node)
    isolatedCycle = isolatedCycle[::-1] # reverse and then take all but last node
    paths.append(isolatedCycle)
return paths            

0 个答案:

没有答案