Implementing Bron–Kerbosch algorithm in python

老子叫甜甜 提交于 2019-12-03 16:14:44
Vaughn Cato

Python is getting confused because you are modifying the list that it is iterating over.

Change

for vertex in p:

to

for vertex in p[:]:

this will cause it to iterate over a copy of p instead.

You can read more about this at http://effbot.org/zone/python-list.htm.

As @VaughnCato correctly points out the error was iterating over P[:]. I thought it worth noting that you can "yield" this result, rather than printing, as follows (in this refactored code):

def bronk2(R, P, X, g):
    if not any((P, X)):
        yield R
    for v in P[:]:
        R_v = R + [v]
        P_v = [v1 for v1 in P if v1 in N(v, g)]
        X_v = [v1 for v1 in X if v1 in N(v, g)]
        for r in bronk2(R_v, P_v, X_v, g):
            yield r
        P.remove(v)
        X.append(v)
def N(v, g):
    return [i for i, n_v in enumerate(g[v]) if n_v]

In [99]: list(bronk2([], range(6), [], graph))
Out[99]: [[0, 1, 4], [1, 2], [2, 3], [3, 4], [3, 5]]

In case someone is looking for a Bron–Kerbosch algorithm implementation in the future...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!