Python:检查一个集合是否可以从另一个集合创建

Python:检查一个集合是否可以从另一个集合创建,python,set,Python,Set,我有一套清单: graphs = [{1, 2, 3}, {4, 5}, {6}] 我必须检查是否可以将输入集创建为图中的集合之和。 例如: input1 = {1, 2, 3, 6} # answer - True input2 = {1, 2, 3, 4} # answer - False, because "4" is only a part of another set, only combinations of full sets are required 换

我有一套清单:

graphs = [{1, 2, 3}, {4, 5}, {6}]
我必须检查是否可以将输入集创建为图中的集合之和。 例如:

input1 = {1, 2, 3, 6} # answer - True
input2 = {1, 2, 3, 4} # answer - False, because "4" is only a part of another set, only combinations of full sets are required 
换句话说,图中有所有集合的组合:

我需要知道,这些组合中的一个是否等于输入


我应该如何正确地迭代图形元素以获得答案?如果图形较大,则查找所有组合时会出现一些问题。

您可以使用itertools.combinations查找所有组合,然后简单地比较集合:

from itertools import combinations, chain

def check(graphs, inp):
    for i in range(1, len(graphs)+1):
        for p in combinations(graphs, i):
            if set(chain(*p)) == inp:
                return True
    return False

graphs = [{1, 2, 3}, {4, 5}, {6}]
input1 = {1, 2, 3, 6}
input2 = {1, 2, 3, 4}

print(check(graphs, input1))
print(check(graphs, input2))
印刷品:

True
False

您可以使用itertools.combines查找所有组合,然后只需比较这些集合:

from itertools import combinations, chain

def check(graphs, inp):
    for i in range(1, len(graphs)+1):
        for p in combinations(graphs, i):
            if set(chain(*p)) == inp:
                return True
    return False

graphs = [{1, 2, 3}, {4, 5}, {6}]
input1 = {1, 2, 3, 6}
input2 = {1, 2, 3, 4}

print(check(graphs, input1))
print(check(graphs, input2))
印刷品:

True
False

我认为你看得不对。我认为最好删除包含不能使用的元素的任何集合,即在查找{1,2,3,4}时删除集合{4,5}。然后创建所有其他集合的并集,看看这是否等于您的输入集合

这样,您就不需要找到所有的组合,只需在开始时执行至多一个镜头集消除步骤

graphs = [i for i in graphs if i.issubset(input1)  ]
检查答案:

result = set().union(*graphs) == input1

我认为你看得不对。我认为最好删除包含不能使用的元素的任何集合,即在查找{1,2,3,4}时删除集合{4,5}。然后创建所有其他集合的并集,看看这是否等于您的输入集合

这样,您就不需要找到所有的组合,只需在开始时执行至多一个镜头集消除步骤

graphs = [i for i in graphs if i.issubset(input1)  ]
检查答案:

result = set().union(*graphs) == input1