Complex Set Operations in Python
By combining short forms of the methods you learned in previous lessons, you can perform quite complex operations on sets.
Let's find the intersections of all three sets:
st1 = {1, 2, 3, 4}
st2 = {3, 4, 1, 6}
st3 = {1, 2, 8, 4}
res = st1 & st2 & st3
print(res) # {1, 4}
Now let's first find out by what elements the first set differs from the second. And then we'll find the intersection of the obtained result with the third set. To indicate the priority of operations, we use grouping brackets:
st1 = {1, 2, 8, 4}
st2 = {3, 4, 5, 6}
st3 = {6, 2, 8, 4}
res = (st1 - st2) & st3
print(res) # {8, 2}
Three sets are given:
st1 = {1, 3, 6, 8}
st2 = {5, 8, 4, 2}
st3 = {4, 7, 3, 1}
Combine the first and third sets. Then find their intersection with the third set.
Four sets are given:
st1 = {4, 2, 6, 10}
st2 = {1, 6, 3, 2}
st3 = {5, 8}
st4 = {6, 3, 1}
Find out the difference between the elements of the first and second sets. Then combine the third and fourth sets. And finally, find the common elements of the sets obtained as a result of the first and second operations.