Exercises
Set Methods
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Print who joined and who left, sorted, using set differences.
Python
before = {"ada", "grace"}
after = {"grace", "kat"}
# print the joiners, then the leavers
after - before gives the new ones.
before = {"ada", "grace"}
after = {"grace", "kat"}
print(sorted(after - before))
print(sorted(before - after))Exercise 2Passed
Remove an item that may not be there, without raising.
Python
tags = {"a", "b"}
# remove "missing" safely, then print the sorted set
One of remove and discard tolerates absence.
tags = {"a", "b"}
tags.discard("missing")
print(sorted(tags))Exercise 3Passed
Use a frozenset so the pair can be a dictionary key, then look it up in the other order.
Python
lookup = {}
# map the pair 1 and 2 to "first", then print the lookup using 2 and 1
A frozenset cannot change, so it hashes.
lookup = {frozenset({1, 2}): "first"}
print(lookup[frozenset({2, 1})])