📅  最后修改于: 2023-12-03 14:46:03.931000             🧑  作者: Mango
set intersection()
The intersection()
method of Python sets is used to obtain the intersection of two or more sets.
The syntax of intersection()
method is as follows:
set1.intersection(set2, set3, ..., setn)
Here, set1
, set2
, set3
... are the sets to be intersected.
The intersection()
method returns a new set containing the common elements of all the sets that are being intersected. If there are no common elements, an empty set is returned.
# creating sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
set3 = {5, 6, 7, 8, 9}
# intersection of sets
set4 = set1.intersection(set2)
set5 = set1.intersection(set2, set3)
print("Intersection of set1 and set2:", set4)
print("Intersection of set1, set2 and set3:", set5)
Output:
Intersection of set1 and set2: {3, 4, 5}
Intersection of set1, set2 and set3: {5}
In the above example, the intersection()
method is used to find the common elements between sets set1
and set2
, as well as between sets set1
, set2
, and set3
. The resulting sets are set4
and set5
, respectively.
The intersection()
method has a time complexity of O(min(n*m)) where n and m are the number of elements in the input sets. In the worst-case scenario, when all sets have the same number of elements, the time complexity becomes O(n^2). The space complexity of the method is O(min(n,m)).
The intersection()
method is a useful tool for obtaining the common elements between two or more sets in Python. Its simplicity and efficiency make the method a popular choice for set operations in Python.