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

时间:2020-10-25 11:05:09

标签: python set

我有一套清单:

str

我必须检查data={"name&numb":["cat 123","34 dog","bird 93","dolphin dof 8 ","lion cat 76","tiger 22 animal "]} df=pd.DataFrame.from_dict(data) 集是否可以作为df["number"]=df["name&numb"].str.extract('(\d+)') 内部集的总和来创建。
例如:

 df["strings"]=df["name&numb"].str.extract('str')

换句话说,graphs = [{1, 2, 3}, {4, 5}, {6}] 中包含集合的所有组合:

input

我需要知道这些组合之一是否等于graphs

如何正确遍历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较大,则查找所有组合会有些问题。

2 个答案:

答案 0 :(得分:3)

我认为您看错了这条路。我认为最好删除包含无法使用的元素的任何集合(例如,在寻找{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

答案 1 :(得分:1)

您可以找到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