如何在Python中检查超集

279 阅读3分钟

在python中,我们使用集合来存储唯一的不可变的对象。在这篇文章中,我们将讨论什么是一个集合的超集。我们还将讨论在Python中检查超集的方法。

什么是超集?

一个集合的超集是包含该集合所有元素的另一个集合。换句话说,如果我们有一个集合A和集合B,并且集合B的每个元素都属于集合A,那么集合A被称为集合B的超集。

让我们考虑一个例子,我们得到了三个集合A、B和C,如下所示。

A={1,2,3,4,5,6,7,8}

B={2,4,6,8}

C={0,1,2,3,4}

在这里,你可以看到集合B中的所有元素都存在于集合A中,因此,集合A是集合B的超集。

你可以看到,一个超集总是比原始集合有更多或相等的元素。现在,让我们描述一个逐步的算法来检查python中的超集。

如何在Python中检查超集?

考虑到我们有两个集合A和B。现在,我们必须检查集合B是否是集合A的超集。为此,我们将遍历集合A的所有元素,检查它们是否存在于集合B中。如果在集合A中存在一个不属于集合B的元素,我们就说集合B不是集合A的超集,否则,集合B就是集合A的超集。

为了在 Python 中实现这种方法,我们将使用一个 for 循环和一个标志变量isSuperset 。我们将初始化isSuperset 变量为 True,表示集合 B 是集合 A 的超集。现在我们将使用 for 循环遍历集合 A。在遍历集合A中的元素时,我们将检查该元素是否存在于集合B中。

isSuperset 如果我们发现A中的任何元素不在集合B中,我们将把False ,表明集合B不是集合A的超集。

如果我们在集合A中没有发现任何不属于集合B的元素,那么isSuperset 变量将包含值True ,表明集合B是集合A的超集。整个检查超集的逻辑可以用Python实现,如下所示。

def checkSuperset(set1, set2):
    isSuperset = True
    for element in set2:
        if element not in set1:
            isSuperset = False
            break
    return isSuperset


A = {1, 2, 3, 4, 5, 6, 7, 8}
B = {2, 4, 6, 8}
C = {0, 1, 2, 3, 4}
print("Set {} is: {}".format("A", A))
print("Set {} is: {}".format("B", B))
print("Set {} is: {}".format("C", C))
print("Set A is superset of B :", checkSuperset(A, B))
print("Set A is superset of C :", checkSuperset(A, C))
print("Set B is superset of C :", checkSuperset(B, C))

输出。

Set A is: {1, 2, 3, 4, 5, 6, 7, 8}
Set B is: {8, 2, 4, 6}
Set C is: {0, 1, 2, 3, 4}
Set A is superset of B : True
Set A is superset of C : False
Set B is superset of C : False

使用 issuperset() 方法检查超集

我们还可以使用 issuperset() 方法来检查Python中的超集。issuperset() 方法,当对一个集合A调用时,接受一个集合B作为输入参数,如果集合A是B的超集,则返回True 。否则,它返回False

你可以使用issuperset() 方法来检查python中的超集,方法如下。

A = {1, 2, 3, 4, 5, 6, 7, 8}
B = {2, 4, 6, 8}
C = {0, 1, 2, 3, 4}
print("Set {} is: {}".format("A", A))
print("Set {} is: {}".format("B", B))
print("Set {} is: {}".format("C", C))
print("Set A is superset of B :", A.issuperset(B))
print("Set A is superset of C :", A.issuperset(C))
print("Set B is superset of C :", B.issuperset(C))

输出。

Set A is: {1, 2, 3, 4, 5, 6, 7, 8}
Set B is: {8, 2, 4, 6}
Set C is: {0, 1, 2, 3, 4}
Set A is superset of B : True
Set A is superset of C : False
Set B is superset of C : False

结论

在这篇文章中,我们讨论了两种在python中检查超集的方法。