These exercises practice what the Module 8 reading explained. They aren’t graded. Work each one on paper first, then check your answer, and only then run the code to confirm it. The answers are in the collapsed blocks; open one only after you have an answer of your own.
Worked example: tracing a count¶
counts = {}
for letter in "abca":
counts[letter] = counts.get(letter, 0) + 1letter | counts.get(letter, 0) | counts after the line |
|---|---|---|
"a" | 0 | {'a': 1} |
"b" | 0 | {'a': 1, 'b': 1} |
"c" | 0 | {'a': 1, 'b': 1, 'c': 1} |
"a" | 1 | {'a': 2, 'b': 1, 'c': 1} |
The second "a" finds its count, 1, and adds one to it. The keys stay in the order they were
first added.
Exercise 8.1 (LO-8.1, ★, about 10 minutes)¶
What does this print?
ages = {"Ana": 31, "Ben": 27}
ages["Chen"] = 35
ages["Ana"] = ages["Ana"] + 1
print(ages)
print(ages.get("Dara"), ages.get("Dara", "unknown"))
print("Ben" in ages, 27 in ages, 27 in ages.values())
print(sorted(ages, key=lambda name: ages[name]))Answer
{'Ana': 32, 'Ben': 27, 'Chen': 35}
None unknown
True False True
['Ben', 'Ana', 'Chen']in on a dictionary looks at the keys, so 27 in ages is False; ages.values() holds the values. The last line sorts the keys, the names, by the value each one maps to.
Exercise 8.2 (LO-8.1, ★★, about 15 minutes)¶
Write invert(d), which returns a new dictionary from each value of d to a list of the keys that
have that value, in order: invert({"tea": 2.5, "jam": 3.0, "milk": 2.5}) is
{2.5: ['tea', 'milk'], 3.0: ['jam']}. Why can’t the result map each value to a single key?
Hint
This is grouping: the group’s key is each pair’s value.
Answer
def invert(d):
"""Return a dictionary from each value of d to the list of keys that have it."""
inverted = {}
for key, value in d.items():
if value not in inverted:
inverted[value] = []
inverted[value].append(key)
return invertedSeveral keys can share a value, as tea and milk do, but a dictionary has each key once, so {2.5: "tea"} would lose milk. The values of d become keys, so they must be values that can’t change: inverting a dictionary whose values are lists stops with a TypeError.
Worked example: reading nested data¶
timetable = {
"Mon": [("09:00", "Maths"), ("11:00", "History")],
"Tue": [("10:00", "Biology")],
}
print(timetable["Mon"][0][1])Read the expression one step at a time. timetable["Mon"] is the list of Monday’s classes;
[0] is the first of them, the tuple ("09:00", "Maths"); and [1] is the subject in that
tuple. It prints Maths.
Exercise 8.3 (LO-8.2, ★★, about 15 minutes)¶
Each order below has a customer and a list of items, and each item is a tuple of a name, a quantity, and a price:
ORDERS = [
{"customer": "Ana", "items": [("tea", 2, 2.50), ("cake", 1, 4.00)]},
{"customer": "Ben", "items": [("coffee", 1, 3.20)]},
{"customer": "Ana", "items": [("cake", 2, 4.00)]},
{"customer": "Chen", "items": [("tea", 1, 2.50), ("coffee", 2, 3.20)]},
]Build
revenue, a dictionary from each customer to the total they spent.Build
tea_buyers, the set of customers who bought tea.
Answer
revenue = {}
tea_buyers = set()
for order in ORDERS:
customer = order["customer"]
for name, quantity, price in order["items"]:
revenue[customer] = revenue.get(customer, 0) + quantity * price
if name == "tea":
tea_buyers.add(customer)
print(revenue)
print(sorted(tea_buyers)){'Ana': 17.0, 'Ben': 3.2, 'Chen': 8.9}
['Ana', 'Chen']The outer loop goes through the orders, and the inner loop through each order’s items, unpacking each tuple. Ana has two orders, so her total uses get, as a count would. Money in floats is approximate (Module 2): compare these totals with math.isclose, and round them only when you print them.
Exercise 8.4 (LO-8.2, ★★, about 10 minutes)¶
The worked example stored a timetable as a dictionary from each day to a list of
(time, subject) tuples. Another program needs to answer one question many times: “What is on at
this time on this day?” Design a structure that answers it with no loop, write the expression for
“10:00 on Tuesday”, and say what the new structure makes harder.
Answer
A dictionary from each day to a dictionary from each time to the subject:
timetable = {
"Mon": {"09:00": "Maths", "11:00": "History"},
"Tue": {"10:00": "Biology"},
}
print(timetable["Tue"]["10:00"])It prints Biology, with two lookups and no searching. timetable["Tue"].get("15:00") gives None for a free slot. What is harder: a day’s classes in order of time need sorted(timetable["Tue"].items()), and a question such as “on which days is Biology?” still needs a loop over every day. The right structure depends on the questions the program asks most.
Worked example: repeats and sets¶
A form collects the tags a user typed, with repeats and mixed case. Remove the repeats, ignoring case, and report which tags are new:
typed = ["Python", "data", "python", "Web", "DATA"]
known = {"python", "web", "games"}
tags = {tag.lower() for tag in typed}
print(sorted(tags))
print(sorted(tags - known))['data', 'python', 'web']
['data']{tag.lower() for tag in typed} is a set comprehension: a list comprehension in curly braces,
which builds a set, so the repeats disappear. tags - known keeps the tags that aren’t known yet.
Exercise 8.5 (LO-8.3, ★, about 10 minutes)¶
What does each expression give?
sorted(set("mississippi"))len(set([1, 2, 2, 3, 3, 3]))sorted({1, 2, 3} - {2, 4})sorted({1, 2, 3} ^ {2, 4}){1, 2} <= {1, 2, 3}type({})
Answer
['i', 'm', 'p', 's']3[1, 3]: the 4 isn’t in the first set, so taking it away changes nothing.[1, 3, 4]: the items in exactly one of the sets.True: every item of{1, 2}is in{1, 2, 3}.<class 'dict'>:{}is an empty dictionary. The empty set isset().
Exercise 8.6 (LO-8.3, ★★, about 15 minutes)¶
Write missing_letters(text), which returns a sorted list of the letters from a to z that don’t
appear in text, in either case. missing_letters("The quick brown fox jumps over the lazy dog")
is [], because that sentence uses every letter.
Answer
def missing_letters(text):
"""Return the letters a-z that don't appear in text, in either case, sorted."""
return sorted(set("abcdefghijklmnopqrstuvwxyz") - set(text.lower()))
print(missing_letters("Hello, world"))['a', 'b', 'c', 'f', 'g', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 's', 't', 'u', 'v', 'x', 'y', 'z']set(text.lower()) holds every character of the text, punctuation included, but subtracting it from the 26 letters leaves only letters. A loop over the alphabet with not in works too, but the set difference says what the function means.
Exercise 8.7 (LO-8.4, ★★, about 15 minutes)¶
Run this code, which looks up the last of 100,000 numbers 1,000 times in each of the four collections, and then times inserting 1,000 numbers at the front of a list and appending 1,000 at its end. Explain the two groups of results.
import timeit
n = 100_000
items_list = list(range(n))
items_tuple = tuple(items_list)
items_set = set(items_list)
items_dict = dict.fromkeys(items_list)
target = n - 1
for name, collection in [("list", items_list), ("tuple", items_tuple),
("set", items_set), ("dict", items_dict)]:
seconds = timeit.timeit(lambda: target in collection, number=1_000)
print(f"{name:<6}{seconds:.6f} s")
front = timeit.timeit("items.insert(0, 0)", setup="items = list(range(100_000))", number=1_000)
back = timeit.timeit("items.append(0)", setup="items = list(range(100_000))", number=1_000)
print(f"insert(0, x): {front:.6f} s append(x): {back:.6f} s")dict.fromkeys(items) makes a dictionary with each item as a key and None as every value. Here
timeit also takes code as a string, with setup, code it runs once before timing.
Answer
On a laptop with an Intel Core i7-11800H processor, running Linux and Python 3.12.3, one run printed:
list 0.645484 s
tuple 0.602361 s
set 0.000045 s
dict 0.000049 s
insert(0, x): 0.019464 s append(x): 0.000012 sThe list and the tuple compare the target with every item, so they take about the same, long, time; the set and the dictionary use the hash, so they take about the same, very short, time. Inserting at the front moves all 100,000 items along one place each time, while appending moves nothing, so insert(0, x) was about 1,600 times as slow here. Your numbers will differ, but the groups won’t.
Exercise 8.8 (LO-8.4, ★★★, about 20 minutes)¶
A sign-up page checks each of 10,000 new usernames against a list of 50,000 names already taken.
Estimate how many comparisons
name not in taken_namesmakes in all, for a list, when most new names aren’t taken.Write
count_available(new_names, taken_names), which returns how many new names aren’t taken, and makes the checks fast whatever typetaken_namesis.Time it against a version that uses the list directly, with 2,000 new names, so the slow version finishes in about a second.
Hint
A name that isn’t taken is compared with every name in the list. Build a set from taken_names once, at the start of the function, not once for each new name.
Answer
A name that isn’t in the list is compared with all 50,000 names, so 10,000 such names make about 10,000 × 50,000 = 500 million comparisons.
and 3.
import timeit
def count_available_list(new_names, taken_names):
"""Return how many of new_names aren't in the list taken_names."""
available = 0
for name in new_names:
if name not in taken_names:
available = available + 1
return available
def count_available(new_names, taken_names):
"""Return how many of new_names aren't in taken_names, using a set."""
taken = set(taken_names)
available = 0
for name in new_names:
if name not in taken:
available = available + 1
return available
taken_names = [f"user{k}" for k in range(50_000)]
new_names = [f"user{k}" for k in range(49_000, 51_000)]
assert count_available(new_names, taken_names) == count_available_list(new_names, taken_names)
list_time = timeit.timeit(lambda: count_available_list(new_names, taken_names), number=1)
set_time = timeit.timeit(lambda: count_available(new_names, taken_names), number=1)
print(f"list: {list_time:.3f} s, set: {set_time:.4f} s")Half of the 2,000 new names are taken, near the end of the list, and half aren’t. On the laptop described in Exercise 8.7, four runs printed between 0.76 and 1.00 s for the list and between 0.0022 and 0.0030 s for the set version, building the set included: more than 300 times as fast. With 10,000 new names, range(49_000, 59_000), two runs took 4.6 and 4.7 s for the list version and less than 0.004 s for the set version. Building the set inside the function means callers can pass a list, a tuple, or a set.