Ciência da computação · Livro 2 · 10.º ao 12.º ano

High School Computer Science

Este livro ainda não está disponível em Português. Edições: English.

High School Computer Science · 10.º ao 12.º ano

2Tuples, Sets and Comprehensions

Dara and Umar both borrow books from the town library, and they wonder whether they have the same taste. The library’s records give each of them a list of loans; a book borrowed twice appears twice. To answer “which books have we both read?” with lists, one has to take each book of Dara’s list and look for it along the whole of Umar’s, and then remove the repeats from the answer.

Python has a type made for this question, the set, where a book is either in or out and never twice. This chapter introduces it, together with the tuple, a fixed group of values such as a point (3,4)(3, 4), and the comprehension, a one-line way to build a list, a set or a dictionary. On the way it answers a question that caused a bug in the previous chapter: why does a function that sorts its argument change the caller’s list?

You already know

A list holds values in order, t[i] reads the value at position i, and t.append(x) adds x at the end (Book 1, grade 7). A dictionary maps keys to values, d[k], and a record of a table is a dictionary from column names to values (Book 1, grade 8). The town library’s tables were met in Book 1; they are read here with town.load("loans"), which returns a list of such records. Sets as mathematical objects belong to the mathematics book; this chapter is about the Python type.

2.1 Tuples

Definition 2.1 (Tuple, unpacking)

A tuple is a sequence of values written between parentheses and separated by commas, such as (3, 4). Like a list it has a length and positions, read with p[i]; unlike a list, it cannot be changed once built. Unpacking assigns the values of a tuple to as many names at once: x, y = p.

point = (3, 4)
print(point, point[0], len(point))

x, y = point
print("x =", x, "y =", y)

a = 1
b = 2
a, b = b, a
print("a =", a, "b =", b)

single = (7,)
not_a_tuple = (7)
print(single, type(single), not_a_tuple, type(not_a_tuple))
Listing 2.1. Building, reading and unpacking tuples. code/grade-10/02-tuples-sets-comprehensions/listings/tuples.py
$ python tuples.py
(3, 4) 3 2
x = 3 y = 4
a = 2 b = 1
(7,) <class 'tuple'> 7 <class 'int'>
Output 2.1. A tuple of one element needs a comma; without it the parentheses are only grouping.

Line 9 is the classic use of unpacking: the right side b, a builds the tuple (2, 1) first, and only then are its two values given to a and b. No third variable is needed to swap two values.

The most common use of a tuple is to return several results from one function. Strictly, a function still returns one value, a tuple; the caller unpacks it.

def min_max(t):
    """Return the smallest and the largest number of the non-empty list t."""
    smallest = t[0]
    largest = t[0]
    for x in t:
        if x < smallest:
            smallest = x
        if x > largest:
            largest = x
    return smallest, largest


low, high = min_max([12, 18, 7, 15, 9])
print("lowest", low, "highest", high)
print(min_max([5]))
Listing 2.2. One loop, two results, returned as a tuple. code/grade-10/02-tuples-sets-comprehensions/listings/min_max.py
$ python min_max.py
lowest 7 highest 18
(5, 5)
Output 2.2. The second call prints the tuple itself.

A tuple whose positions have fixed meanings (a title, an author, a year) is a record. Numbers are easy to mix up; names are not.

Definition 2.2 (Named tuple)

A named tuple is a tuple whose positions also have names, so that b.year and b[2] read the same value. In Python, namedtuple("Book", ["title", "author", "year"]), from the module collections, creates a new type Book of such tuples.

from collections import namedtuple

Book = namedtuple("Book", ["title", "author", "year"])

b = Book("The Silent Code", "Fatou Dalewell", 2002)
print(b)
print(b.title, "was published in", b.year)
print(b[2] == b.year)
title, author, year = b
print(author)
Listing 2.3. A record of the town library as a named tuple. code/grade-10/02-tuples-sets-comprehensions/listings/named.py
$ python named.py
Book(title='The Silent Code', author='Fatou Dalewell', year=2002)
The Silent Code was published in 2002
True
Fatou Dalewell
Output 2.3. A named tuple prints its field names, and still unpacks like any tuple.

A dictionary could hold the same record. The named tuple is fixed: it always has the same three fields and they cannot be changed, which is what a record read from a table usually needs.

2.2 Mutable and immutable values

Definition 2.3 (Mutable, immutable)

A value is mutable when it can be changed after it is built, and immutable when it cannot. Lists, dictionaries and sets are mutable. Numbers, strings and tuples are immutable: an operation on them builds a new value.

scores = [12, 18, 7]
scores[0] = 13
print(scores)

point = (3, 4)
point[0] = 5
print(point)
Listing 2.4. The same assignment on a list and on a tuple. code/grade-10/02-tuples-sets-comprehensions/listings/immutable.py
$ python immutable.py
[13, 18, 7]
Traceback (most recent call last):
  File "immutable.py", line 6, in <module>
    point[0] = 5
    ~~~~~^^^
TypeError: 'tuple' object does not support item assignment
[exit status 1]
Output 2.4. Changing a position of a tuple is refused.

The difference matters because of the way Python names values. A variable does not contain a list; it refers to a list stored somewhere in memory. The assignment b = a does not copy anything: it makes b refer to the same list as a.

Definition 2.4 (Alias)

Two names are aliases when they refer to the same value in memory. The test a is b is true exactly when a and b are aliases; the test a == b compares the contents of two values, which may be distinct.

a = [1, 2, 3]
b = a
b.append(4)
print("a:", a, " b:", b, " a is b:", a is b)

c = list(a)
c.append(5)
print("a:", a, " c:", c, " a is c:", a is c)
print("a == [1, 2, 3, 4]:", a == [1, 2, 3, 4])
Listing 2.5. An alias and a copy. code/grade-10/02-tuples-sets-comprehensions/listings/alias.py
$ python alias.py
a: [1, 2, 3, 4]  b: [1, 2, 3, 4]  a is b: True
a: [1, 2, 3, 4]  c: [1, 2, 3, 4, 5]  a is c: False
a == [1, 2, 3, 4]: True
Output 2.5. A change made through b is seen through a; a change made to the copy c is not.

The figure below draws the memory after line 7: names on the left, values on the right, an arrow for “refers to”.

Names refer to values. a and b are aliases of one list; c refers to a copy, which changes on its own.
Names refer to values. a and b are aliases of one list; c refers to a copy, which changes on its own.

This explains the bug of the previous chapter: inside largest_three(t), the parameter t is an alias of the caller’s list, so t.sort() sorts the caller’s list. Aliases of an immutable value are harmless, since nobody can change it; aliases of a mutable value are where side effects come from.

A copy made by list(a), or by the slice a[:], is a new list holding the same elements. When those elements are themselves lists, they are not copied: the new outer list refers to the same inner lists.

Definition 2.5 (Shallow copy, deep copy)

A shallow copy of a value is a new value whose parts refer to the same objects as the parts of the original. A deep copy copies the parts too, and their parts, all the way down, so that it shares nothing mutable with the original. In Python, list(a) and a[:] make shallow copies, and copy.deepcopy(a) makes a deep copy.

import copy

grid = [[0, 0, 0], [0, 0, 0]]
shallow = list(grid)
deep = copy.deepcopy(grid)

shallow[0][0] = 9
deep[1][2] = 7
print("grid:   ", grid)
print("shallow:", shallow)
print("deep:   ", deep)
print(shallow[0] is grid[0], deep[0] is grid[0])
Listing 2.6. A grid of two rows, copied two ways. code/grade-10/02-tuples-sets-comprehensions/listings/copy_nested.py
$ python copy_nested.py
grid:    [[9, 0, 0], [0, 0, 0]]
shallow: [[9, 0, 0], [0, 0, 0]]
deep:    [[0, 0, 0], [0, 0, 7]]
True False
Output 2.6. The change through the shallow copy reaches the original grid.
After the listing: grid and its shallow copy are two outer lists sharing the same two rows, so the 9 written through shallow is seen through grid; the deep copy has rows of its own.
After the listing: grid and its shallow copy are two outer lists sharing the same two rows, so the 9 written through shallow is seen through grid; the deep copy has rows of its own.

2.3 Sets

Definition 2.6 (Set (Python type))

A set is a collection of values without order and without repeats. It is written between braces, {1, 2, 3}, or built from any sequence with set(t); the empty set is set(), since {} is an empty dictionary. The test x in s says whether x belongs to s, s.add(x) adds an element, and the operators &, | and - give the intersection, the union and the difference of two sets.

genres_ana = set(["mystery", "sport", "history", "mystery"])
genres_ben = {"poetry", "sport", "science"}

print(genres_ana)
print(len(genres_ana), "sport" in genres_ana, "poetry" in genres_ana)
print("both:  ", genres_ana & genres_ben)
print("either:", genres_ana | genres_ben)
print("only Ana:", genres_ana - genres_ben)

seen = set()
for word in ["to", "be", "or", "not", "to", "be"]:
    seen.add(word)
print(len(seen), "different words")
Listing 2.7. The genres two readers like, as sets. code/grade-10/02-tuples-sets-comprehensions/listings/sets.py
$ python sets.py
{'history', 'mystery', 'sport'}
3 True False
both:   {'sport'}
either: {'history', 'mystery', 'poetry', 'science', 'sport'}
only Ana: {'history', 'mystery'}
4 different words
Output 2.7. The repeated "mystery" is kept once; the order in which a set prints is Python’s choice.

Two properties of sets are worth keeping in mind. First, a set has no positions: s[0] is an error, and the order in which a set of strings prints can differ from one computer to another. To print a set in a fixed order, print sorted(s), which is a list. Second, the test x in s is fast, whatever the size of the set, whereas x in t on a list compares x with the elements one by one; grade 11 measures the difference.

The elements of a set, like the keys of a dictionary, must be immutable: Python files each element by a number computed from its value, and that number would be wrong if the value could change afterwards. A tuple can be such a key; a list cannot.

walls = {(0, 1): "wall", (2, 3): "door"}
print(walls[(2, 3)])
print((0, 1) in walls, (1, 0) in walls)

walls[[4, 4]] = "window"
Listing 2.8. The cells of a maze, keyed by their coordinates. code/grade-10/02-tuples-sets-comprehensions/listings/tuple_key.py
$ python tuple_key.py
door
True False
Traceback (most recent call last):
  File "tuple_key.py", line 5, in <module>
    walls[[4, 4]] = "window"
    ~~~~~^^^^^^^^
TypeError: unhashable type: 'list'
[exit status 1]
Output 2.8. Python calls a value that may serve as a key hashable; a list is not.

Now the question of the introduction. The function below gathers the books one member borrowed into a set, so that a book borrowed twice counts once, and the operator & does the rest.

import town

loans = town.load("loans")


def books_of(member):
    """Return the set of the ids of the books that member borrowed."""
    result = set()
    for loan in loans:
        if loan["member_id"] == member:
            result.add(loan["book_id"])
    return result


first = books_of(40)
second = books_of(55)
print("member 40:", sorted(first))
print("member 55:", sorted(second))
print("both:     ", sorted(first & second))
print("sizes:", len(first), len(second), len(first & second), len(first | second))
Listing 2.9. Which books have members 40 and 55 both borrowed? code/grade-10/02-tuples-sets-comprehensions/listings/shared_books.py
$ python shared_books.py
member 40: [16, 29, 57, 62, 71, 75]
member 55: [9, 11, 16, 34, 46, 57, 60, 62, 71, 72, 75]
both:      [16, 57, 62, 71, 75]
sizes: 6 11 5 12
Output 2.9. Member 40 is Dara, member 55 is Umar.
The two members’ sets of books, with the counts printed by the run (the five shared books are 16, 57, 62, 71 and 75). The union holds 6 + 11 - 5 = 12 books: the shared ones would otherwise be counted twice.
The two members’ sets of books, with the counts printed by the run (the five shared books are 16, 57, 62, 71 and 75). The union holds 6+11−5=126 + 11 - 5 = 12 books: the shared ones would otherwise be counted twice.

2.4 Comprehensions

Many loops build a new collection from an old one: the squares of a list of numbers, the even ones, the first letter of each word. Python has a shorter notation for them.

Definition 2.7 (Comprehension)

A comprehension is an expression that builds a list, a set or a dictionary from a sequence: [e for x in t] is the list of the values of the expression e for each element x of t, in order; [e for x in t if c] keeps only the elements for which the condition c is true. With braces, {e for x in t} builds a set and {k: v for x in t} a dictionary.

A comprehension is read from the middle: the loop, then the condition, then the expression, which comes first in the writing. On the right, the loop it stands for.
A comprehension is read from the middle: the loop, then the condition, then the expression, which comes first in the writing. On the right, the loop it stands for.
numbers = [4, 7, 10, 3, 8]

squares = [n * n for n in numbers]
evens = [n for n in numbers if n % 2 == 0]
print(squares)
print(evens)

words = ["map", "graph", "path", "grid", "maze"]
first_letters = {w[0] for w in words}
lengths = {w: len(w) for w in words}
print(sorted(first_letters))
print(lengths)

pairs = [(r, c) for r in range(2) for c in range(3)]
print(pairs)
Listing 2.10. List, set and dictionary comprehensions. code/grade-10/02-tuples-sets-comprehensions/listings/comprehensions.py
$ python comprehensions.py
[16, 49, 100, 9, 64]
[4, 10, 8]
['g', 'm', 'p']
{'map': 3, 'graph': 5, 'path': 4, 'grid': 4, 'maze': 4}
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
Output 2.10. The last comprehension has two for: the second varies fastest, as in two nested loops.

The set comprehension on line 9 removes the repeated m and g by itself; the dictionary comprehension on line 10 maps each word to its length.

Example 2.8 (The books of a member, in one line)

The function books_of of the town listing is the set comprehension {loan["book_id"] for loan in loans if loan["member_id"] == member}: for each loan, if it is the member’s, put its book in the set.

Remark 2.9 (When a loop is clearer)

A comprehension is for building a collection and nothing else. When each step must also print, count, stop early (break) or update several variables, a loop is clearer; and a comprehension that no longer fits on one line is usually better written as a loop. The test is the reader: if the comprehension cannot be read aloud as one sentence, it should be a loop.

Method 2.10 (Choosing a collection)

  1. A fixed group of values that belong together (a point, a date, a record): a tuple or a named tuple.
  2. Values in an order that matters, possibly repeated, possibly changing: a list.
  3. Membership questions (“is it there?”, “what is common?”) with no order and no repeats: a set.
  4. Values looked up by a key: a dictionary.

2.5 Exercises

Exercise 2.1 ★

What do these lines print? a, b, c = (1, 2, 3), then a, c = c, a, then print(a, b, c). What happens with x, y = (1, 2, 3)?

Solution

Solution of Exercise 2.1.

After the first line a, b, c are 11, 22, 33; the second line builds the tuple (3, 1) and gives 33 to a and 11 to c: the line prints 3 2 1. With x, y = (1, 2, 3) there are three values for two names: Python stops with ValueError: too many values to unpack.

Exercise 2.2 ★

With s = {1, 2, 3, 4} and t = {3, 4, 5}, give s & t, s | t, s - t, t - s, len(s | t) and 5 in s.

Solution

Solution of Exercise 2.2.

s & t is {3, 4}, s | t is {1, 2, 3, 4, 5}, s - t is {1, 2}, t - s is {5}, len(s | t) is 55, and 5 in s is False.

Exercise 2.3 ★

Write a function first_last(t) that returns the first and the last element of a non-empty list as a tuple, with its specification, and a call that unpacks the result into two names.

Solution

Solution of Exercise 2.3.

def first_last(t): with the docstring “Return the first and the last element of t. Precondition: t is a non-empty list.” and the body return t[0], t[-1]. A call: first, last = first_last([4, 8, 1]) gives first the value 44 and last the value 11. For a list of one element both are that element.

Exercise 2.4 ★

What does this print? t = [1, 2], u = t, v = t[:], u.append(3), v.append(4), then print(t, u, v, t is u, t is v, t == u). Draw the memory as in the figure on aliases.

Solution

Solution of Exercise 2.4.

u is an alias of t; v is a copy. The line prints [1, 2, 3] [1, 2, 3] [1, 2, 4] True False True. The drawing has two lists: t and u point to [1, 2, 3], v to [1, 2, 4].

Exercise 2.5 ★

Explain why len(a | b) == len(a) + len(b) - len(a & b) for any two sets, and check it on the run of the town listing. When is len(a | b) equal to len(a) + len(b)?

Solution

Solution of Exercise 2.5.

len(a) + len(b) counts every element of the union once, except those of the intersection, which belong to both sets and are counted twice; subtracting len(a & b) counts them once. On the town run: 6+11−5=126 + 11 - 5 = 12, the size printed for the union. The union has len(a) + len(b) elements exactly when a & b is empty.

Exercise 2.6 ★★

A student writes colours = ("red") and then for c in colours: print(c), hoping to print one colour. What does the loop print, and why? Correct the first line.

Solution

Solution of Exercise 2.6.

("red") is only the string "red" in parentheses, and a loop over a string goes through its characters: it prints r, e, d on three lines. The tuple of one element is written ("red",), with the comma.

Exercise 2.7 ★★

Write common_books(loans, a, b), which returns the set of the ids of the books borrowed both by member a and by member b, using two set comprehensions. Check it on members 4040 and 5555.

Solution

Solution of Exercise 2.7.

The file exercises/common_books.py builds the set of the books of member a as

books_a = {loan["book_id"] for loan in loans if loan["member_id"] == a}

and books_b the same way with b; the function returns books_a & books_b. For members 4040 and 5555 it returns {16, 57, 62, 71, 75}, as the town listing printed (checked by the chapter’s tests).

Exercise 2.8 ★★

To make a 3×33 \times 3 grid of zeros, a student writes grid = [[0] * 3] * 3, then grid[0][0] = 1, and prints [[1, 0, 0], [1, 0, 0], [1, 0, 0]]. Explain with a memory drawing, and build the grid with a comprehension instead.

Solution

Solution of Exercise 2.8.

[0] * 3 builds one list [0, 0, 0]; multiplying the outer list by 33 repeats the reference to it, so the grid is an outer list of three arrows to the same row. Writing through grid[0] changes that row, which is also grid[1] and grid[2]. The comprehension [[0] * 3 for _ in range(3)] evaluates [0] * 3 three times and builds three rows (exercises/grid_bug.py).

Exercise 2.9 ★★

What do these print? {w: w.upper() for w in ["a", "b"]}, then {n % 3 for n in range(10)}, then {n: n * n for n in range(4) if n != 2}.

Solution

Solution of Exercise 2.9.

{"a": "A", "b": "B"}; then the set of the remainders, {0, 1, 2}; then {0: 0, 1: 1, 3: 9}, where the key 22 is left out by the condition.

Exercise 2.10 ★★

A comprehension can list all the subsets of ["a", "b", "c", "d"]. Without running it, how many are there? Explain the count by deciding, element by element, whether it is in or out, and say how many subsets have exactly two elements.

Solution

Solution of Exercise 2.10.

A subset is fixed by deciding, for each of the four elements, whether it is in or out: 22 choices for "a", times 22 for "b", and so on, so 2×2×2×2=162 \times 2 \times 2 \times 2 = 16 subsets, from the empty set to the whole set. The subsets of two elements are the pairs ab, ac, ad, bc, bd, cd: 66. The comprehension of exercises/subsets.py lists the 1616 (checked by the chapter’s tests).

Exercise 2.11 ★★

Write distinct_authors(books), which returns the set of the authors of a list of book records, and authors_in_genre(books, genre), which returns the sorted list of the authors of at least one book of the genre. How many distinct authors does the town library have?

Solution

Solution of Exercise 2.11.

The function distinct_authors is one set comprehension,

return {book["author"] for book in books}

and authors_in_genre adds the condition if book["genre"] == genre to it and passes the set to sorted (exercises/distinct_authors.py). The town library’s 8080 books have 2323 distinct authors.

Exercise 2.12 ★★★

Without sets, the common books of two lists a and b are found by taking each element of a and comparing it with the elements of b one by one until a match is found. (a) What is the largest number of comparisons for lists of 66 and 1111 books? (b) When is it reached? (c) For two lists of nn elements each, what is the largest number, and how does it change when nn doubles?

Solution

Solution of Exercise 2.12.

(a) Each of the 66 elements of a is compared with at most the 1111 elements of b: at most 6×11=666 \times 11 = 66 comparisons. (b) It is reached when no element of a is found before the end of b: for example when the lists have nothing in common. (c) n×n=n2n \times n = n^2; when nn doubles, the largest number is multiplied by 44. With sets, x in s does not go through s, which is why the set version is much faster on large lists (exercises/count_intersection.py counts the comparisons).

Exercise 2.13 ★★★

Write transpose(table), which returns the transpose of a rectangular list of rows (row ii of the result is column ii of the table), as a single nested comprehension. Check that transposing twice gives back the table.

Solution

Solution of Exercise 2.13.

return [[row[j] for row in table] for j in range(len(table[0]))]: the outer comprehension goes through the column numbers, the inner one collects the value of that column in each row. On [[1, 2, 3], [4, 5, 6]] it gives [[1, 4], [2, 5], [3, 6]], and transposing that gives the table back (exercises/transpose.py).

Exercise 2.14 ★★★

A game computes the next state of a grid of 0 and 1 by flipping every cell. Its function starts with new = list(grid) and writes new[r][c] = 1 - grid[r][c] for every cell. The game shows the right next state, but the previous state, kept by the caller for an “undo” button, has changed too. Find the cause and fix it.

Solution

Solution of Exercise 2.14.

list(grid) is a shallow copy: new is a new outer list, but its rows are the rows of grid. Writing new[r][c] writes into the caller’s rows, so the “undo” state changes with the new one. The fix is a deep copy, new = copy.deepcopy(grid), or the comprehension new = [list(row) for row in grid], which copies each row (exercises/grid_copy.py; the tests check that the caller’s grid is untouched).

Exercise 2.15 ★★★

The Jaccard index of two sets AA and BB, not both empty, is ∣A∩B∣/∣A∪B∣|A \cap B| / |A \cup B|: the share of their union that they have in common. Write jaccard(a, b), which returns it as an exact fraction (fractions.Fraction), with an assertion on its precondition. What are its smallest and largest possible values, and when are they reached?

Solution

Solution of Exercise 2.15.

In exercises/jaccard.py: assert a | b, "two empty sets have no Jaccard index", then return Fraction(len(a & b), len(a | b)). The intersection is part of the union, so the index lies between 00 and 11. It is 00 when the sets have no element in common, and 11 when the intersection is the whole union, that is, when the two sets are equal.

2.6 Problem: Readers Alike

Problem 2.1

Weekend problem — which two members read most alike?

The town library wants to start a reading club and pair up members with similar tastes. It measures how alike two readers are with the Jaccard index of their sets of borrowed books (Exercise 2.15). The program exercises/readers_alike.py of this chapter’s code does the computation; the questions follow it step by step.

Part I — One set per member.

  1. The program builds a dictionary books from each member id to a set of book ids, with books.setdefault(m, set()).add(b). Explain what setdefault does here (look it up with help(dict.setdefault)), and why a set is used rather than a list.
  2. The library recorded 400400 loans. Run the program: how many members borrowed at least one book, and how many different books were borrowed?
  3. Why can the total of the sizes of the members’ sets be smaller than 400400?
  4. Write the dictionary books as a dictionary comprehension whose values are set comprehensions, and say why this version is slower than the loop of the program.

Part II — Two members.

  1. From the run of the town listing, give the sizes of the sets of members 4040 and 5555, of their intersection and of their union.
  2. Compute the Jaccard index of members 4040 and 5555 as a fraction, then as a decimal to three places.
  3. Give the Jaccard index of a member with herself, and of two members with no book in common.
  4. Member 3232 borrowed one book, member 4747 two, and they share one. Compute their index.

Part III — All the pairs.

  1. The program lists the pairs with the comprehension [... for i in ids for j in ids if i < j]. Why the condition i < j?
  2. How many pairs are there for 6060 members? Give the count as a formula in the number nn of members.
  3. The pairs are sorted with the key (-value, i, j). Explain how this tuple orders them, and why the two last components are there.
  4. Run the program. Which pair comes first among all 6060 members, and with which index?
  5. Explain why this pair says little about taste.
  6. The program then keeps only the members with at least 55 books. How many members and how many pairs are left?

Part IV — The closest readers.

  1. Which pair comes first among the members with at least 55 books, and with which index?
  2. Which pairs come next, and how far behind?
  3. Show that the Jaccard index of a set of 66 elements and a set of 1111 elements is at most 6/116/11, and say when it reaches that value. How far is the pair 4040 and 5555 from it?
  4. How many comparisons of two sets does the program make for the members with at least 55 books?
  5. Check the first place with a different method: itertools.combinations(ids, 2) lists the same pairs; take the max of the indices.
  6. State the result: the two members whose borrowed books are most alike, with their index as a fraction and a decimal, and the number of books each borrowed.
Solution

Solution of Problem 2.1.

1. books.setdefault(m, set()) returns books[m] if the key m is already there; otherwise it first stores an empty set under m and returns it. Then .add(b) puts the book in that set. A set is used because a book borrowed twice must count once, and because & and | are needed next.

2. 6060 members borrowed at least one book, and 8080 different books were borrowed.

3. A member who borrowed the same book twice has it once in her set. On the town data the sizes add up to 388388: twelve loans repeat a book already borrowed by the same member.

4. With ids = {l["member_id"] for l in loans}, the dictionary is {m: {l["book_id"] for l in loans if l["member_id"] == m} for m in ids}. For each of the 6060 members, the inner comprehension goes through all 400400 loans: 24,00024{,}000 steps instead of the 400400 of the loop.

5. Sizes 66 and 1111; intersection 55; union 1212.

6. 5/12≈0.4175/12 \approx 0.417.

7. With herself: 11, since a set and itself have the same intersection and union. With no common book: 00.

8. Intersection 11, union 22: the index is 1/21/2.

9. Without it, each pair would appear twice (i, j and j, i), and each member would be paired with herself, with the index 11.

10. Each of the nn members is paired with the n−1n - 1 others, and each pair is then counted twice: n(n−1)/2n(n-1)/2 pairs, that is 60×59/2=1,77060 \times 59 / 2 = 1{,}770.

11. Tuples compare position by position, like words in a dictionary. The first component is the index with a minus sign, so a larger index comes first; when two pairs have the same index, the member ids decide, so the order never depends on chance.

12. Members 3232 and 4747, with 1/2=0.5001/2 = 0.500.

13. It rests on one shared book: member 3232 borrowed a single book. With so few books, one coincidence gives a large index. Indices of very small sets are not evidence of a common taste.

14. 4949 members and 49×48/2=1,17649 \times 48 / 2 = 1{,}176 pairs.

15. Members 4040 and 5555, with 5/12≈0.4175/12 \approx 0.417.

16. Members 1515 and 5656, and members 3131 and 4343, both with 1/3≈0.3331/3 \approx 0.333, about 0.080.08 behind the first pair.

17. The intersection has at most 66 elements (it is part of the smaller set), and the union at least 1111 (it contains the larger one): the index is at most 6/11≈0.5456/11 \approx 0.545. It reaches it exactly when the set of 66 is contained in the set of 1111. The pair 4040 and 5555 misses it by one book: one of Dara’s six books is not among Umar’s.

18. One per pair: 1,1761{,}176.

19. The maximum over itertools.combinations(ids, 2) is again 5/125/12 (checked by the chapter’s tests).

20. Among the members with at least 55 books, the two who read most alike are Dara Reedfield (member 4040, 66 books) and Umar Daleton (member 5555, 1111 books): they share 55 books, and their Jaccard index is 5/12≈0.4175/12 \approx 0.417, ahead of the next pairs at 1/31/3.

Termos definidos neste capítulo

Ver todos os 1050 termos do glossário