11e. Review: Tuples#

A review of Chapter 11: Tuples, for students who have already studied the chapter. Use the two lists under Concepts covered as a checklist (click a list’s title to hide it), then work through the Questions, which go from the easiest to the hardest. Each question has a suggested answer under Answer. Try the question first, then open the Answer.

Run this page on Colab

Concepts covered#

Questions#

All the questions use only tuples, dictionaries, lists, strings, loops, functions and print.

The setup cell below imports math.

# Setup for the questions below (imports, downloads of helper files, ...)
import math

Question 1 (easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

t = 'l', 'u', 'p', 'i', 'n'
print(t)
print(len(t))

Question 2 (easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

t1 = 'p',
t2 = ('p')
print(t1)
print(t2)
print(type(t1))
print(type(t2))

Question 3 (easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

print(tuple())
print(tuple('lupin'))
print(tuple([1, 2, 3]))

Question 4 (easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

t = tuple('lupin')
print(t[0])
print(t[1:3])
print(t[-1])

Question 5 (easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

print(tuple('lup') + ('i', 'n'))
print(tuple('ab') * 2)

Question 6 (easy): what happens?#

Predict what happens when this code runs, then open the Answer to check.

t = tuple('lupin')
t[0] = 'L'

Question 7 (easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

grid = {}
grid[1, 2] = 3
grid[3, 4] = 7
print(grid)
print(grid[1, 2])

Question 8 (easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

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

Question 9 (easy): what happens?#

Predict what happens when this code runs, then open the Answer to check.

a, b = 1, 2, 3

Question 10 (easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

d = {'one': 1, 'two': 2}
for key, value in d.items():
    print(key, '->', value)

Question 11 (easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

quotient, remainder = divmod(7, 3)
print(quotient)
print(remainder)

Question 12 (easy): write a function#

Write a function called first_and_last that takes a tuple t and returns a tuple of its first and last elements.

Start from this header (replace ... with the body):

def first_and_last(t):
    ...

Examples

print(first_and_last(('a', 'b', 'c')))
('a', 'c')
print(first_and_last((7,)))
(7, 7)

Question 13 (easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

for index, element in enumerate('abc'):
    print(index, element)

Question 14 (medium): what is displayed?#

Both parts loop through the items in a dictionary and display each key and its value. Part a unpacks each item on its own line. Part b unpacks it in the for line. Predict what each part displays, then open the Answer to check.

Part a

counts = {'a': 1, 'b': 2}
for item in counts.items():
    key, value = item
    print(key, '->', value)

Part b

counts = {'a': 1, 'b': 2}
for key, value in counts.items():
    print(key, '->', value)

Question 15 (medium): write a function#

Write a function called min_max that takes a sequence t and returns a tuple of its smallest and largest elements.

Start from this header (replace ... with the body):

def min_max(t):
    ...

Examples

print(min_max([2, 4, 1, 3]))
(1, 4)
print(min_max('banana'))
('a', 'n')

Question 16 (medium): write a function#

Write a function called make_dict that takes a list of keys and a list of values, and returns a dictionary that maps each key to the value in the same position.

Start from this header (replace ... with the body):

def make_dict(keys, values):
    ...

Examples

print(make_dict(['a', 'b'], [1, 2]))
{'a': 1, 'b': 2}
print(make_dict('abc', [1, 2, 3]))
{'a': 1, 'b': 2, 'c': 3}

Question 17 (hard): write a function#

Write a function called mean that takes any number of arguments and returns their mean: their sum divided by how many there are.

Start from this header (replace ... with the body):

def mean(*args):
    ...

Examples

print(mean(1, 2, 3))
2.0
print(mean(1, 2, 3, 10))
4.0

Question 18 (hard): write a function#

Write a function called invert_dict that takes a dictionary d and returns its inverse: a new dictionary that maps each value in d to a list of the keys that had that value.

Start from this header (replace ... with the body):

def invert_dict(d):
    ...

Examples

print(invert_dict({'p': 1, 'a': 1, 'r': 2, 'o': 1, 't': 1}))
{1: ['p', 'a', 'o', 't'], 2: ['r']}
print(invert_dict({'a': 1, 'b': 2, 'c': 1}))
{1: ['a', 'c'], 2: ['b']}

Question 19 (hard): what is displayed?#

< compares tuples element by element, from the first. It stops at the first pair that differs, and later elements are not considered. Predict what this code displays, then open the Answer to check.

print((0, 1, 2) < (0, 3, 4))
print((0, 1, 2000000) < (0, 3, 4))

Question 20 (hard): write a function#

Write a function called most_common that takes a dictionary counter that maps each key to a count, and returns the key with the largest count.

Start from this header (replace ... with the body):

def most_common(counter):
    ...

Examples

print(most_common({'b': 1, 'a': 3, 'n': 2}))
a
print(most_common({'p': 4, 'q': 2}))
p

Question 21 (hard): write a function#

Write a function called trimmed_mean that takes any number of arguments, removes the lowest and the highest, and returns the mean of the rest. This question uses min_max from Question 15 and mean from Question 17.

Start from this header (replace ... with the body):

def trimmed_mean(*args):
    ...

Examples

print(trimmed_mean(1, 2, 3, 10))
2.5
print(trimmed_mean(5, 1, 4, 2, 3))
3.0

Question 22 (hard): write a function#

Imagine a short book: a list of lines, where each line is a string of words separated by spaces. All the words are lowercase, and there is no punctuation. Write a function called make_index that takes a list of lines and returns a dictionary. Each key is a word in the book, and its value is a list of the line numbers where the word appears. Line numbers start at 1. Each line number appears once in a list, even if the word appears more than once on that line. The method line.split() returns a list of the words in line.

Start from this header (replace ... with the body):

def make_index(lines):
    ...

Examples

print(make_index(['cats sit', 'dogs sit', 'cats sleep']))
{'cats': [1, 3], 'sit': [1, 2], 'dogs': [2], 'sleep': [3]}
print(make_index(['one fish', 'two fish', 'red fish', 'blue fish']))
{'one': [1], 'fish': [1, 2, 3, 4], 'two': [2], 'red': [3], 'blue': [4]}

Question 23 (hard): write a function#

The cell below defines a small book, lines, and its index, index: the dictionary that Question 22 builds, which maps each word to a list of its line numbers.

Run this cell to assign lines and index.

lines = ['cats sit', 'dogs sit', 'cats sleep', 'dogs sleep', 'cats dream']
index = {'cats': [1, 3, 5], 'sit': [1, 2], 'dogs': [2, 4], 'sleep': [3, 4], 'dream': [5]}

Write a function called find_in_book that takes lines, index and a word, and returns a list of windows: one window for each line where the word appears. A window is a list of tuples. Each tuple is a line number and the line itself, for the line where the word appears and the two lines before it and the two lines after it. At the start and the end of the book, the window is shorter: it holds only the lines that exist. If the word is not in the index, the function returns an empty list. Line numbers start at 1.

Start from this header (replace ... with the body):

def find_in_book(lines, index, word):
    ...

Examples

print(find_in_book(lines, index, 'dream'))
[[(3, 'cats sleep'), (4, 'dogs sleep'), (5, 'cats dream')]]
print(find_in_book(lines, index, 'cats'))
[[(1, 'cats sit'), (2, 'dogs sit'), (3, 'cats sleep')], [(1, 'cats sit'), (2, 'dogs sit'), (3, 'cats sleep'), (4, 'dogs sleep'), (5, 'cats dream')], [(3, 'cats sleep'), (4, 'dogs sleep'), (5, 'cats dream')]]
print(find_in_book(lines, index, 'fish'))
[]

Question 24 (hard): write a function#

Write a function called words_on_line that takes an index and a line number, and returns a list of the words that appear on that line. The index is a dictionary like the one Question 22 builds: each key is a word, and its value is a list of the line numbers where the word appears. If no word appears on the line, the function returns an empty list.

Start from this header (replace ... with the body):

def words_on_line(index, number):
    ...

Examples

print(words_on_line({'cats': [1, 3], 'sit': [1, 2], 'dogs': [2]}, 1))
['cats', 'sit']
print(words_on_line({'cats': [1, 3], 'sit': [1, 2], 'dogs': [2]}, 2))
['sit', 'dogs']
print(words_on_line({'cats': [1, 3], 'sit': [1, 2], 'dogs': [2]}, 4))
[]

Question 25 (hard): write a function#

Write a function called find_phrase that takes a list of lines and two words, and returns a list of tuples. Each tuple is a line number and a word number for a place where the two words appear next to each other, in order, on that line. Line numbers and word numbers both start at 1. As in Question 22, the lines hold lowercase words separated by spaces, and line.split() returns a list of the words in line.

Start from this header (replace ... with the body):

def find_phrase(lines, word1, word2):
    ...

Examples

print(find_phrase(['cats sit still', 'dogs sit', 'cats sit'], 'cats', 'sit'))
[(1, 1), (3, 1)]
print(find_phrase(['cats sit still', 'dogs sit', 'cats sit'], 'sit', 'still'))
[(1, 2)]
print(find_phrase(['cats sit still', 'dogs sit', 'cats sit'], 'dogs', 'cats'))
[]

Summary and questions by Prof. Y. Rosenthal, based on Think Python: 3rd Edition by Allen B. Downey. Text license: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International