我試圖實現Bron–Kerbosch algorithm,即列出給定圖中的所有最大派系。在python中實現Bron-Kerbosch算法
我想實現第一種算法(不轉動),但在測試它的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], [])
任何幫助爲什麼我只能得到答案的一部分?
第一件事情 - 沒有爲值比較使用'is' - 那就是''==是 –
我建議不要使用遞歸的副作用(遞歸本身是棘手足以讓那些圍繞頭!)。 *另外,你可以使用list comprehension和['enumerate']來編寫'N'(http://docs.python.org/2/library/functions.html#enumerate)。* –