Exercises
Sets
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Print how many unique names there are.
Python
names = ["Ada", "Grace", "Ada", "Katherine"]
# print the number of unique names
A set drops duplicates.
names = ["Ada", "Grace", "Ada", "Katherine"]
print(len(set(names)))Exercise 2Passed
Remove duplicates but keep the first-seen order.
Python
names = ["Ada", "Grace", "Ada", "Katherine"]
# print them unique and in order
Dictionary keys are unique and ordered.
names = ["Ada", "Grace", "Ada", "Katherine"]
print(list(dict.fromkeys(names)))Exercise 3Passed
Print who joined and who left between the two sets, sorted.
Python
before = {"ada", "grace"}
after = {"grace", "katherine"}
# print the joiners, then the leavers
Set difference answers both questions.
before = {"ada", "grace"}
after = {"grace", "katherine"}
print(sorted(after - before))
print(sorted(before - after))