Practice: lists, sets, and dictionaries#
This lab introduces no new concept. It practises the patterns from Lists, loops, conditionals, and functions and Sets, dictionaries, and data organization, one at a time.
Most exercises use the same small catalogue of books. Each book is a list with three items: title, author, and year of publication.
books = [
["Mrs Dalloway", "Virginia Woolf", 1925],
["Le città invisibili", "Italo Calvino", 1972],
["Pride and Prejudice", "Jane Austen", 1813],
["Il nome della rosa", "Umberto Eco", 1980],
["Frankenstein", "Mary Shelley", 1818],
["To the Lighthouse", "Virginia Woolf", 1927],
["Die Verwandlung", "Franz Kafka", 1915],
["Gulliver's Travels", "Jonathan Swift", 1726],
["Se una notte d'inverno un viaggiatore", "Italo Calvino", 1979],
["Orlando", "Virginia Woolf", 1928],
["Le Comte de Monte-Cristo", "Alexandre Dumas", 1844],
]
Part 1: Loops that build a result#
Many functions follow the same shape: create an empty result before the loop, update it inside the loop, and return it after the loop.
Exercise 1.1: Count the older books#
Write a function count_before(books, year) that returns how many books were published before year.
print(count_before(books, 1900)) # Expected: 4
print(count_before(books, 1800)) # Expected: 1
Solution
def count_before(books, year):
count = 0
for book in books:
if book[2] < year:
count += 1
return count
The counter starts at 0 before the loop, grows by one for every book that matches, and leaves the function only after the loop has visited every book.
Exercise 1.3: Find the oldest book#
Write a function oldest_book(books) that returns the title of the oldest book, without using min().
print(oldest_book(books)) # Expected: Gulliver's Travels
Solution
def oldest_book(books):
oldest = books[0]
for book in books:
if book[2] < oldest[2]:
oldest = book
return oldest[0]
The variable oldest starts from the first book, which is the oldest one among those seen before the loop starts. It changes twice during the loop: at “Pride and Prejudice” (1813) and then at “Gulliver’s Travels” (1726). The variable holds the whole book; for this reason, the function can compare years with oldest[2] and still return the title with oldest[0].
Exercise 1.4: Find the bugs#
This function should count the books published before year, but count_before(books, 1900) returns 0. Find the two bugs.
def count_before(books, year):
for book in books:
count = 0
if book[2] < year:
count += 1
return count
Solution
def count_before(books, year):
count = 0 # Fixed: before the loop
for book in books:
if book[2] < year:
count += 1
return count # Fixed: after the loop
count = 0sits inside the loop, which means the counter starts again from zero at every book.return countsits inside the loop as well. The function ends during the first iteration, after looking only at “Mrs Dalloway” (1925), which is not older than 1900.
The indentation of a line decides whether it runs once or once per item: lines that prepare or return the result belong outside the loop.
Exercise 1.5: Predict the output#
What does this code print?
line = "Nevermore, said the raven."
for char in ",.":
line.replace(char, "")
print(line)
Solution
Nevermore, said the raven.
The text does not change. Strings cannot be modified: replace() returns a new string and leaves the original as it is. The loop builds the new string twice and throws it away both times, because nothing stores it. Assigning the result back to the variable fixes the code:
line = "Nevermore, said the raven."
for char in ",.":
line = line.replace(char, "")
print(line) # Nevermore said the raven
Part 2: Sets#
Exercise 2.1: Find the missing letters#
A pangram is a sentence that uses every letter of the alphabet. A lipogram does the opposite: it leaves out one or more letters on purpose, like Georges Perec’s novel La Disparition (1969), written without the letter “e”.
Write a function missing_letters(text) that returns, in alphabetical order, the letters of the English alphabet that do not appear in text, ignoring case.
print(missing_letters("vedrò compirsi il miracolo: il nulla alle mie spalle, il vuoto dietro di me, con un terrore di ubriaco."))
# Expected: ['f', 'g', 'h', 'j', 'k', 'q', 'w', 'x', 'y', 'z']
print(missing_letters("Nevermore, said the raven."))
# Expected: ['b', 'c', 'f', 'g', 'j', 'k', 'l', 'p', 'q', 'u', 'w', 'x', 'y', 'z']
Solution
def missing_letters(text):
alphabet = set("abcdefghijklmnopqrstuvwxyz")
used = set(text.lower())
return sorted(alphabet.difference(used))
used also contains spaces, punctuation marks, and accented letters such as “ò”, but they do not matter: the difference keeps only the items of alphabet that are not in used. sorted() turns the result into a list in alphabetical order, which makes the output predictable: printing a set directly can show its items in any order.
Exercise 2.2: The anagram trap#
Two words are anagrams when they use the same letters the same number of times, like “roma” and “amor”. Write a function is_anagram(word1, word2) that returns True when the two words are anagrams and False otherwise.
print(is_anagram("roma", "amor")) # Expected: True
print(is_anagram("roma", "rome")) # Expected: False
print(is_anagram("anna", "nan")) # Expected: False
Solution
def is_anagram(word1, word2):
return sorted(word1) == sorted(word2)
sorted() turns each word into the list of its letters in alphabetical order: sorted("roma") and sorted("amor") both give ['a', 'm', 'o', 'r']. A sorted list keeps the duplicates, which means sorted("anna"), ['a', 'a', 'n', 'n'], differs from sorted("nan"), ['a', 'n', 'n'].
Comparing set(word1) with set(word2) would fail on this last pair: both become {'a', 'n'}, because a set records which letters appear and forgets how many times.
Part 3: Dictionaries#
Exercise 3.1: Look up a value#
This dictionary stores the birth year of each author:
birth_years = {
"Jonathan Swift": 1667,
"Jane Austen": 1775,
"Mary Shelley": 1797,
"Alexandre Dumas": 1802,
"Virginia Woolf": 1882,
"Franz Kafka": 1883,
"Italo Calvino": 1923,
"Umberto Eco": 1932,
}
For every book in the catalogue, print the title and the approximate age of the author at publication.
# Expected (first three lines):
# Mrs Dalloway: Virginia Woolf was about 43
# Le città invisibili: Italo Calvino was about 49
# Pride and Prejudice: Jane Austen was about 38
Solution
for book in books:
title = book[0]
author = book[1]
year = book[2]
age = year - birth_years[author]
print(f"{title}: {author} was about {age}")
The author’s name, taken from the list, becomes the key that opens the dictionary. The age is approximate because the code subtracts years and ignores the months: Mary Shelley, for example, was born in August 1797 and published “Frankenstein” in January 1818, at 20.
Exercise 3.2: Count with a dictionary#
Write a function count_by_author(books) that returns a dictionary from each author to the number of their books.
print(count_by_author(books))
# Expected: {'Virginia Woolf': 3, 'Italo Calvino': 2, 'Jane Austen': 1, 'Umberto Eco': 1, 'Mary Shelley': 1, 'Franz Kafka': 1, 'Jonathan Swift': 1, 'Alexandre Dumas': 1}
Solution
With in:
def count_by_author(books):
counts = {}
for book in books:
author = book[1]
if author in counts:
counts[author] += 1
else:
counts[author] = 1
return counts
With get():
def count_by_author(books):
counts = {}
for book in books:
author = book[1]
counts[author] = counts.get(author, 0) + 1
return counts
Both versions follow the shape of Part 1: an empty dictionary before the loop, an update inside, a return after. The if is necessary in the first version because counts[author] += 1 raises a KeyError when the author is not yet a key. get(author, 0) handles both cases in one line: it returns the current count, or 0 the first time the author appears.
Exercise 3.3: Group items into lists#
Write a function titles_by_author(books) that returns a dictionary from each author to the list of their titles, in catalogue order.
groups = titles_by_author(books)
print(groups["Virginia Woolf"]) # Expected: ['Mrs Dalloway', 'To the Lighthouse', 'Orlando']
print(groups["Mary Shelley"]) # Expected: ['Frankenstein']
Solution
def titles_by_author(books):
groups = {}
for book in books:
author = book[1]
if author not in groups:
groups[author] = []
groups[author].append(book[0])
return groups
Each value is a list. The first time an author appears, the function creates an empty list for them; every time, including the first, it appends the title to that list. The if has no else, because the append() must run in both cases.