gpt4 book ai didi

python - 在 python 中实现 Bron–Kerbosch 算法

转载 作者:太空狗 更新时间:2023-10-30 00:25:22 32 4
gpt4 key购买 nike

对于一个大学项目,我正在尝试实现 Bron–Kerbosch algorithm ,即列出给定图中的所有最大团。

我正在尝试实现第一个算法(不旋转),但我的代码在 Wikipedia's example 上测试后并没有给出所有答案。 ,到目前为止我的代码是:

# 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], [])

为什么我只得到部分答案有什么帮助吗?

最佳答案

Python 变得很困惑,因为您正在修改它正在迭代的列表。

改变

for vertex in p:

for vertex in p[:]:

这将导致它迭代 p 的副本。

您可以在 http://effbot.org/zone/python-list.htm 阅读更多相关信息.

关于python - 在 python 中实现 Bron–Kerbosch 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13904636/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com