如何修改Bron-KerBosch算法以根据集团大小输出集团列表列表(或列表字典)?

例如对于此处-https://stackoverflow.com/a/59339555/7865680的参考实现,

N = {
    i: set(num for num, j in enumerate(row) if j)
    for i, row in enumerate(adj_matrix)
}

print(N)
# {0: {1, 4}, 1: {0, 2, 4}, 2: {1, 3}, 3: {2, 4, 5}, 4: {0, 1, 3}, 5: {3}}

def BronKerbosch1(P, R=None, X=None):
    P = set(P)
    R = set() if R is None else R
    X = set() if X is None else X
    if not P and not X:
        yield R
    while P:
        v = P.pop()
        yield from BronKerbosch1(
            P=P.intersection(N[v]), R=R.union([v]), X=X.intersection(N[v]))
        X.add(v)

P = N.keys()
print(list(BronKerbosch1(P)))
# [{0, 1, 4}, {1, 2}, {2, 3}, {3, 4}, {3, 5}]

查看图表

enter image description here

它应该输出,而不是

[{0, 1, 4}, {1, 2}, {2, 3}, {3, 4}, {3, 5}]

列表列表(集)

[ [[1, 2], [2, 3], [3, 4], [3, 5]], [[0, 1, 4]] ]

或列表(集合)的词典

{ "2": [[1, 2], [2, 3], [3, 4], [3, 5]], "3": [[0, 1, 4]]]

推荐答案

要获取列表的字典,您可以在过程中将其设置为bootstrap,并仅在结束时返回它:

def BronKerbosch1(P, R=None, X=None, grp={}):
    P = set(P)
    R = R or set()
    X = X or set()
        
    if not P and not X:
        grp.setdefault(len(R), []).append(list(R))
        
    while P:
        v = P.pop()
        grp = BronKerbosch1(
            P=P.intersection(N[v]), R=R.union([v]), X=X.intersection(N[v]))
        X.add(v)
    
    return grp

发帖主题:Re:Kolibrios

out = BronKerbosch1(P)

print(out) # {3: [[0, 1, 4]], 2: [[1, 2], [2, 3], [3, 4], [3, 5]]}

如果键(i.e, sizes)的顺序很重要,请使用dict(sorted(BronKerbosch1(P).items())):

print(out) # {2: [[1, 2], [2, 3], [3, 4], [3, 5]], 3: [[0, 1, 4]]}

Python相关问答推荐

Python -按第一个条目减go 日期?

将每个关键字值对转换为pyspark中的Intramame列

如何随着收件箱的增加动态添加到HTML表的右下角?

在for循环中保存和删除收件箱

为什么我的主页不会重定向到详细视图(Django)

在Python中,如何才能/应该使用decorator 来实现函数多态性?

收件箱转换错误- polars.exceptions. ComputeHelp- pandera(0.19.0b3)带有polars

是什么导致对Python脚本的jQuery Ajax调用引发500错误?

使用regex分析具有特定字符的字符串(如果它们存在)

为什么dict(id=1,**{id:2})有时会引发KeyMessage:id而不是TypMessage?

Pydantic:如何将对象列表表示为dict(将列表序列化为dict)

Polars:使用列值引用when / then表达中的其他列

pandas DataFrame GroupBy.diff函数的意外输出

Pandas 滚动最接近的价值

在Google Colab中设置Llama-2出现问题-加载判断点碎片时Cell-run失败

使用索引列表列表对列进行切片并获取行方向的向量长度

将数据框架与导入的Excel文件一起使用

处理带有间隙(空)的duckDB上的重复副本并有效填充它们

pandas在第1列的id,第2列的标题,第3列的值,第3列的值?

如何使用Numpy. stracards重新编写滚动和?