python - 创建派系图以确定独立集

标签 python graph-theory

尝试将 s 派转变为 s 独立派。下面是代码,最底部的函数“independent_set_decision(H,s)”是我正在努力解决的问题。我知道我需要创建该图的补充,然后检查该图是否是一个派系。但是,我编写的函数并未按预期创建图表。有人对这段代码有什么问题有什么建议吗?

# Returns a list of all the subsets of a list of size k
def k_subsets(lst, k):
    if len(lst) < k:
        return []
    if len(lst) == k:
        return [lst]
    if k == 1:
        return [[i] for i in lst]
    return k_subsets(lst[1:],k) + map(lambda x: x + [lst[0]], k_subsets(lst[1:], k-1))

# Checks if the given list of nodes forms a clique in the given graph.
def is_clique(G, nodes):
    for pair in k_subsets(nodes, 2):
        if pair[1] not in G[pair[0]]:
            return False
    return True

# Determines if there is clique of size k or greater in the given graph.
def k_clique_decision(G, k):
    nodes = G.keys()
    for i in range(k, len(nodes) + 1):
        for subset in k_subsets(nodes, i):
            if is_clique(G, subset):
                return True
    return False

def make_link(G, node1, node2):
    if node1 not in G:
        G[node1] = {}
    (G[node1])[node2] = 1
    if node2 not in G:
        G[node2] = {}
    (G[node2])[node1] = 1
    return G

def break_link(G, node1, node2):
    if node1 not in G:
        print "error: breaking link in a non-existent node"
        return
    if node2 not in G:
        print "error: breaking link in a non-existent node"
        return
    if node2 not in G[node1]:
        print "error: breaking non-existent link"
        return
    if node1 not in G[node2]:
        print "error: breaking non-existent link"
        return
    del G[node1][node2]
    del G[node2][node1]
    return G

# This function should use the k_clique_decision function
# to solve the independent set decision problem
def independent_set_decision(H, s):
    nodes = H.keys()
    I = {}
    for node1 in nodes:
        for node2 in H[node1]:
            if (H[node1])[node2] != 1:
                make_link(I,node1,node2)

    return k_clique_decision(I, s)

最佳答案

            if (H[node1])[node2] != 1:

您的图形表示并不表示具有非 1 值的缺失链接。它表示由于根本不包含相关的字典条目而丢失了链接。迭代所有节点,而不仅仅是具有链接的节点,并检查 node2 是否是 H[node1] 中的键:

for node1 in H:
    for node2 in H:
        if node2 not in H[node1]:
            make_link(I, node1, node2)

关于python - 创建派系图以确定独立集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22394164/

相关文章:

python - QtDesigner - 在 Windows 7 下缺少功能?

python - 文档脚本不是狮身人面像中模块的一部分

python - 过滤掉张量中的非零值

matlab - 如何在Matlab中绘制网络?

c++ - 拓扑排序中的邻接表表示

python - 将同一行中的值按相同的值拆分为多列中的 df?

python - pygame粒子: issues removing from list

algorithm - 将后序二叉树遍历索引转换为层序(广度优先)索引

algorithm - 树的分而治之算法

algorithm - 在有向图中检测循环的最佳算法