创建团图以确定独立集

1 投票
1 回答
683 浏览
提问于 2025-04-17 22:14

我正在尝试把一个s-clique(s-团)转换成一个s-independent set(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)

1 个回答

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

你的图的表示方式并没有用非1的值来表示缺失的链接。它是通过根本不包含相关的字典条目来表示链接缺失的。你应该遍历所有的节点,而不仅仅是那些有链接的节点,然后检查一下 node2 是否是 H[node1] 的一个键:

撰写回答