Comparing Sets
Sets are made for comparing. Anna and Tom are ordering a pizza together, and each of them has a set of the toppings they like:
anna = {"cheese", "ham", "mushrooms"}
tom = {"cheese", "salami", "mushrooms", "corn"}
print(anna & tom)
print(anna | tom)
print(anna - tom)
print(tom - anna){'mushrooms', 'cheese'}
{'salami', 'mushrooms', 'ham', 'corn', 'cheese'}
{'ham'}
{'salami', 'corn'}Three operators compare two sets, and each of them gives a new set:
anna & tom(and) holds the values that are in both sets: the toppings both of them like.anna | tom(or) holds the values that are in at least one of them, each once: everything that someone likes.anna - tom(minus) holds the values of the first set that aren't in the second: what only Anna likes. Here the order matters:tom - annais what only Tom likes.
The sets anna and tom themselves stay as they were. And the order of the values in each printed set can differ from run to run, as with any set of texts.
When no value is in both sets, the result is an empty set, which prints as set(): {"ham"} & {"corn"} is set().
The result is a set like any other, so len() and in work on it: len(anna | tom) is the number of all the toppings, 5.
Instructions
- 1
Print who came on both days, with
&:Both days:and the set. The output isBoth days: {'Tom', 'Eva'}, or with the names the other way round. Keep the two lines with the sets: the exercise also tries other days. - 2
Print how many different people came during the week, with
|andlen():People: 5. - 3
Finally, print who came on Monday but not on Thursday:
Only Monday:and the set,{'Anna', 'Max'}in either order.