为了账号安全,请及时绑定邮箱和手机立即绑定

Python:检查一组是否可以从另一组创建

Python:检查一组是否可以从另一组创建

元芳怎么了 2023-12-29 15:35:40
我有套装清单:graphs = [{1, 2, 3}, {4, 5}, {6}]我必须检查是否input可以将集合创建为内部集合的总和graphs。例如:input1 = {1, 2, 3, 6} # answer - Trueinput2 = {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}{1, 2, 3, 6}{1, 2, 3, 4, 5}{4, 5, 6}{1, 2, 3, 4, 5, 6}我需要知道这些组合之一是否等于input.我应该如何正确地迭代graphs元素以获得答案?如果graphs更大,找到所有组合就会出现一些问题。
查看完整描述

2 回答

?
婷婷同学_

TA贡献1844条经验 获得超8个赞

我认为你看待这个问题的方式是错误的。我认为最好删除包含无法使用的元素的任何集合(即{4,5}在查找时删除集合{1,2,3,4}。然后创建union所有其他集合并查看这是否等于您的输入集合。

这样,您将不需要找到所有组合,只需首先执行(最多)O(n*len(sets)) 消除步骤。

graphs = [i for i in graphs if i.issubset(input1)  ]

检查答案:

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


查看完整回答
反对 回复 2023-12-29
?
慕容森

TA贡献1853条经验 获得超18个赞

您可以找到 的所有组合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


查看完整回答
反对 回复 2023-12-29
  • 2 回答
  • 0 关注
  • 50 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信