---
# SPDX-FileCopyrightText: 2026 Arcangelo Massari <arcangelo.massari@unibo.it>
#
# SPDX-License-Identifier: CC-BY-4.0

jupytext:
  text_representation:
    extension: .md
    format_name: myst
kernelspec:
  display_name: Python 3
  language: python
  name: python3
---

(ch-lab-13)=
# Practice: lists, sets, and dictionaries

This lab introduces no new concept. It practises the patterns from {ref}`ch-lab-03` and {ref}`ch-lab-04`, 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.

```python
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`.

```python
print(count_before(books, 1900))  # Expected: 4
print(count_before(books, 1800))  # Expected: 1
```

````{admonition} Solution
:class: dropdown

```python
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.2: Collect the titles of an author

Write a function `titles_by(books, author)` that returns a list with the titles of all the books by `author`, in catalogue order.

```python
print(titles_by(books, "Umberto Eco"))      # Expected: ['Il nome della rosa']
print(titles_by(books, "Dante Alighieri"))  # Expected: []
```

````{admonition} Solution
:class: dropdown

```python
def titles_by(books, author):
    titles = []
    for book in books:
        if book[1] == author:
            titles.append(book[0])
    return titles
```

The shape matches the previous exercise: an empty list takes the place of the counter, and `append()` takes the place of `+= 1`.
````

### Exercise 1.3: Find the oldest book

Write a function `oldest_book(books)` that returns the title of the oldest book, without using `min()`.

```python
print(oldest_book(books))  # Expected: Gulliver's Travels
```

````{admonition} Solution
:class: dropdown

```python
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.

```python
def count_before(books, year):
    for book in books:
        count = 0
        if book[2] < year:
            count += 1
        return count
```

````{admonition} Solution
:class: dropdown

```python
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 = 0` sits inside the loop, which means the counter starts again from zero at every book.
- `return count` sits 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?

```python
line = "Nevermore, said the raven."
for char in ",.":
    line.replace(char, "")
print(line)
```

````{admonition} Solution
:class: dropdown

```
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:

```python
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.

```python
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']
```

````{admonition} Solution
:class: dropdown

```python
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.

```python
print(is_anagram("roma", "amor"))  # Expected: True
print(is_anagram("roma", "rome"))  # Expected: False
print(is_anagram("anna", "nan"))   # Expected: False
```

````{admonition} Solution
:class: dropdown

```python
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:

```python
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.

```python
# 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
```

````{admonition} Solution
:class: dropdown

```python
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.

```python
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}
```

````{admonition} Solution
:class: dropdown

With `in`:

```python
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()`:

```python
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.

```python
groups = titles_by_author(books)
print(groups["Virginia Woolf"])  # Expected: ['Mrs Dalloway', 'To the Lighthouse', 'Orlando']
print(groups["Mary Shelley"])    # Expected: ['Frankenstein']
```

````{admonition} Solution
:class: dropdown

```python
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.
````

### Exercise 3.4: Find the most prolific author

Start from the counts of Exercise 3.2:

```python
counts = count_by_author(books)
```

Write a function `most_prolific(counts)` that returns the author with the most books, without using `max()`.

```python
print(most_prolific(counts))  # Expected: Virginia Woolf
```

````{admonition} Solution
:class: dropdown

```python
def most_prolific(counts):
    best_author = ""
    best_count = 0
    for author, count in counts.items():
        if count > best_count:
            best_author = author
            best_count = count
    return best_author
```

The function repeats the idea of Exercise 1.3: it keeps the best item found so far. `items()` gives each author together with their count, and the function needs both: the count to compare, the author to return. Every author has at least one book, which means any of them beats the starting count of `0`.
````
