在python中实现Bron–Kerbosch算法 [英] Implementing Bron–Kerbosch algorithm in python

查看:141
本文介绍了在python中实现Bron–Kerbosch算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个大学项目,我正在尝试实现 Bron-Kerbosch算法,也就是说,列出给定图中的所有最大集团.

for a college project I'm trying to implement the Bron–Kerbosch algorithm, that is, listing all maximal cliques in a given graph.

我正在尝试实现第一个算法(无枢轴),但是我的代码在

I'm trying to implement the first algorithm (without pivoting) , but my code doesn't yield all the answers after testing it on the Wikipedia's example , my code so far is :

# dealing with a graph as list of lists 
graph = [[0,1,0,0,1,0],[1,0,1,0,1,0],[0,1,0,1,0,0],[0,0,1,0,1,1],[1,1,0,1,0,0],[0,0,0,1,0,0]]


#function determines the neighbors of a given vertex
def N(vertex):
    c = 0
    l = []
    for i in graph[vertex]:
        if i is 1 :
         l.append(c)
        c+=1   
    return l 

#the Bron-Kerbosch recursive algorithm
def bronk(r,p,x):
    if len(p) == 0 and len(x) == 0:
        print r
        return
    for vertex in p:
        r_new = r[::]
        r_new.append(vertex)
        p_new = [val for val in p if val in N(vertex)] # p intersects N(vertex)
        x_new = [val for val in x if val in N(vertex)] # x intersects N(vertex)
        bronk(r_new,p_new,x_new)
        p.remove(vertex)
        x.append(vertex)


    bronk([], [0,1,2,3,4,5], [])

对我为什么只得到部分答案的任何帮助吗?

Any help why I'm getting only a part of the answer ?

推荐答案

Python感到困惑,因为您正在修改要迭代的列表.

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

更改

for vertex in p:

for vertex in p[:]:

这将导致它遍历p的副本.

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

您可以在 http://effbot.org/zone/python-list上了解有关此内容的更多信息.htm .

这篇关于在python中实现Bron–Kerbosch算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆