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.

Run this page on Colab

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):
    ...

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):
    ...

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):
    ...

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):
    ...

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):
    ...

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):
    ...

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):
    ...

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):
    ...

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):
    ...

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