9e. Review: Sentences, Nested Loops and Tables#
More practice after Chapter 9: Lists. These questions use what you have already learned — for loops, if statements, lists, and string methods — and they build on each other. Nested loops were introduced in 9c; opening a file was introduced in 7c.
Try each question first, then open its Answer.
Practice questions#
Question 1 (medium): write a function#
Write a function called split_sentences that takes a list of lines from a book and returns a list of the book’s sentences.
A sentence may start on one line and finish on a later line, and one line may contain more than one sentence. A sentence ends with a period, a question mark, or an exclamation point.
For example:
split_sentences(["Hello world. How are",
"you today? I am",
"fine!"])
# ['Hello world.', 'How are you today?', 'I am fine!']
Rules, so there is no guessing:
Join the lines first, with a single space between lines, so words split across lines do not run together, and so a sentence that spans lines comes back as one sentence. Ignore blank lines.
A piece of text with no ending mark at the end is not a complete sentence, so leave it out.
Simplification — read this carefully: for this question, assume that every period ends a sentence. Do NOT worry about abbreviations such as “Mr.” or “Mrs.”, or about acronyms such as “U.S.A.” — in real books those periods do not end a sentence, but here you may treat every period as a sentence ending. That means
split_sentences(["Mr. Smith went home."])returns['Mr.', 'Smith went home.'], and that is correct for this question.
Hint: the string method split makes a list from a string by splitting on a character — for example, 'a.b.c'.split('.') gives ['a', 'b', 'c']. You may split on a period, a question mark, or an exclamation point — but remember that split throws the character you split on away, so if you use it, you must put the ending mark back on each sentence, or you will lose that text. Splitting is not the only way to do this; the Answer shows two ways.
Start from this header (replace ... with the body):
def split_sentences(lines):
...
Answer
Solution 1 (mark the ends, then split):
def split_sentences(lines):
words = []
for line in lines:
stripped = line.strip()
if stripped:
words.append(stripped)
text = ' '.join(words)
for end in '.?!':
text = text.replace(end, end + '\n')
sentences = []
for piece in text.split('\n'):
piece = piece.strip()
if piece and (piece.endswith('.') or piece.endswith('?') or piece.endswith('!')):
sentences.append(piece)
return sentences
After joining the lines, every ending mark gets a newline put right after it. Splitting on the newline then gives one piece per sentence, with its ending mark still attached. The last if drops a final piece with no ending mark.
Solution 2 (walk the text, one character at a time):
def split_sentences(lines):
words = []
for line in lines:
stripped = line.strip()
if stripped:
words.append(stripped)
text = ' '.join(words)
sentences = []
current = ''
for ch in text:
current += ch
if ch in '.?!':
sentences.append(current.strip())
current = ''
return sentences
current collects one sentence. The if inside the for is the whole decision: when the character is an ending mark, the sentence is finished, so it is added to the list and current starts over. A leftover current with no ending mark is never added, which is exactly the rule above. Both solutions pass all the examples in the question.
Question 2 (medium): write a function#
Write a function called sentences_from_file that takes the name of a book file, reads the book, and returns the list of its sentences, by calling the function from Question 1. Do not copy Question 1’s code into this function.
Start from this header (replace ... with the body):
def sentences_from_file(filename):
...
Answer
def sentences_from_file(filename):
f = open(filename)
lines = []
for line in f:
stripped = line.strip()
if stripped:
lines.append(stripped)
return split_sentences(lines)
sentences_from_file does only the file part — opening the file and making a list of its lines — and hands the list to split_sentences, which does only the sentence part. If the sentence rules change, only Question 1’s function changes.
Question 3 (easy, then hard): write functions#
(a) Write a function called count_questions that takes a list of sentences (in the form Question 1 returns) and returns how many of them are questions. For example, count_questions(['Are you ready?', 'Yes!', 'Hello.']) is 1.
(b) (hard) Write a function called longest_sentence that returns the longest sentence in the list, or '' if the list is empty. This is the same shape — a for loop, an if that compares lengths — with a different decision inside the loop.
Start from these headers (replace ... with the bodies):
def count_questions(sentences):
...
def longest_sentence(sentences):
...
Answer
(a)
def count_questions(sentences):
count = 0
for sentence in sentences:
if sentence.endswith('?'):
count += 1
return count
(b)
def longest_sentence(sentences):
longest = ''
for sentence in sentences:
if len(sentence) > len(longest):
longest = sentence
return longest
Question 4 (hard, in two parts): write functions#
Nested loops were introduced in 9c: a loop inside another loop, where the inner loop runs to completion for every single pass of the outer loop.
Part A: print it. Write a function called checkerboard_print that prints a checkerboard of rows rows and cols columns, using '*' and ' '. The top-left character is '*'.
For example, checkerboard_print(2, 3) prints:
* *
*
Hint: a character is '*' when its row plus its column is even.
Start from this header (replace ... with the body):
def checkerboard_print(rows, cols):
...
Answer
def checkerboard_print(rows, cols):
for r in range(rows):
line = ''
for c in range(cols):
if (r + c) % 2 == 0:
line += '*'
else:
line += ' '
print(line)
The inner loop builds one row, character by character, and the if inside the inner loop decides each character.
Question 4 (hard, in two parts): write a function — Part B#
Part B: return it as a list instead of printing it. Modify Part A’s function so that, instead of printing each row, it returns a list of strings, one string per row. Call it checkerboard_rows.
For example, checkerboard_rows(2, 3) is ['* *', ' * '].
Start from this header (replace ... with the body):
def checkerboard_rows(rows, cols):
...
Answer
With every change marked, line by line:
def checkerboard_rows(rows, cols): # CHANGED: new name, for the new job
rows_list = [] # ADDED: the list to collect the rows
for r in range(rows): # UNCHANGED
line = '' # UNCHANGED
for c in range(cols): # UNCHANGED
if (r + c) % 2 == 0: # UNCHANGED
line += '*' # UNCHANGED
else: # UNCHANGED
line += ' ' # UNCHANGED
rows_list.append(line) # ADDED: save the finished row
return rows_list # ADDED: hand the list back
# DELETED: print(line) — printing is gone; the row is saved instead.
What did NOT change: the two loops, the if/else that decides each character, and the way line is built, character by character. What changed: the function name, and the last step of each outer pass. What was added: the empty list at the start, append, and return. What was deleted: the print call, and nothing else.
Question 5 (hard, in two parts): write functions#
Part A: print the pairs. Write a function called print_even_pairs that prints, one pair per line, every pair (i, j) with i and j each from 1 through n, whose sum is even.
For example, print_even_pairs(2) prints:
1 1
2 2
Start from this header (replace ... with the body):
def print_even_pairs(n):
...
Answer
def print_even_pairs(n):
for i in range(1, n+1):
for j in range(1, n+1):
if (i + j) % 2 == 0:
print(i, j)
Question 5 (hard, in two parts): write a function — Part B#
Part B: return the pairs as a list instead of printing them. Modify Part A’s function so that, instead of printing each pair, it returns a list of pairs, where each pair is a list [i, j]. Call it even_pairs.
For example, even_pairs(3) is [[1, 1], [1, 3], [2, 2], [3, 1], [3, 3]].
Start from this header (replace ... with the body):
def even_pairs(n):
...
Answer
With every change marked, line by line:
def even_pairs(n): # CHANGED: new name, for the new job
pairs = [] # ADDED: the list to collect the pairs
for i in range(1, n+1): # UNCHANGED
for j in range(1, n+1): # UNCHANGED
if (i + j) % 2 == 0: # UNCHANGED
pairs.append([i, j]) # CHANGED: was print(i, j); now save [i, j]
return pairs # ADDED: hand the list back
# DELETED: print(i, j) — printing is gone; the pair is saved instead.
What did NOT change: the two loops and the if that tests the sum. What changed: the function name, and the action inside the if (print became append). What was added: the empty list at the start and return. What was deleted: the print call, and nothing else.
Question 6 (hard, in two parts): write functions#
A list of lists can hold a table: each inner list is one row, and each item in a row is one cell. For example:
table = [['Name', 'Age', 'City'],
['Ada', '36', 'London'],
['Bo', '7', 'New York']]
Part A: first pass — one row per line. Write a function called print_grid that prints a table like this, one row per line, with a single space between the items in a row.
For example, print_grid(table) prints:
Name Age City
Ada 36 London
Bo 7 New York
Start from this header (replace ... with the body):
def print_grid(grid):
...
Answer
def print_grid(grid):
for row in grid:
cells = []
for item in row:
cells.append(str(item))
print(' '.join(cells))
str(item) matters: a cell may be a number, and join needs strings. This version is easy to read, but the columns do not line up, because the items have different lengths — 'New York' is longer than 'Bo', so the next column starts in a different place on each row.
Question 6 (hard, in two parts): write a function — Part B#
Part B: second pass — every item in the same width. Modify Part A’s function so that the columns line up. First work out the widest item in the whole table (the longest string, once every item has been turned into a string), then print every item padded to that width, with a single space between items. Call it print_grid_aligned.
For example, print_grid_aligned(table) prints (trailing spaces at the end of a row are harmless):
Name Age City
Ada 36 London
Bo 7 New York
Now 'Age' starts in the same column on every row, and so does 'City', because every item takes up 8 characters (the width of 'New York') plus the separating space.
Hint: a string method, ljust, pads a string on the right to a given width — 'Ada'.ljust(8) is 'Ada '. You must still turn numbers into strings first.
Start from this header (replace ... with the body):
def print_grid_aligned(grid):
...
Answer
With every change marked, line by line:
def print_grid_aligned(grid): # CHANGED: new name, for the new job
width = 0 # ADDED: the widest item, so far
for row in grid: # ADDED: first pass over the table
for item in row: # ADDED: inner loop over the cells
if len(str(item)) > width: # ADDED: is this item wider?
width = len(str(item)) # ADDED: then it is the new widest
for row in grid: # UNCHANGED
cells = [] # UNCHANGED
for item in row: # UNCHANGED
cells.append(str(item).ljust(width)) # CHANGED: was str(item); now str(item).ljust(width)
print(' '.join(cells)) # UNCHANGED
# DELETED: nothing, except the idea that one pass is enough.
# Part B needs two passes: one to find the width, one to print.
What did NOT change: the outer loop over the rows, joining a row’s items with a single space, and turning each item into a string. What changed: the function name, and the item in the join (now padded). What was added: the whole first pair of nested loops that finds width. What was deleted: nothing from Part A’s printing logic — it is still there, with padding added to it.
Why two passes are needed: you cannot pad an item to the widest width until you know what the widest width is, and you only know that after you have looked at every item. A version that pads each column to its own widest item is possible, and is even neater, but it is not asked for here — here every item gets the same width, the widest item in the whole table.
Credits#
More review questions by Prof. Y. Rosenthal, for Think Python: 3rd Edition by Allen B. Downey. Text license: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International