9g. Review: Practice Programs#

Practice programs after Chapter 9: Lists, for a review of Chapters 1 to 9. Many questions ask you to write a function that Python already has (for example count, index, find, split, join and replace), with only loops, if statements, indexes and slices. Some questions practice if, elif and else, and nested if statements. Many questions after Question 17 use a nested loop (9c), and some of them use a function that you wrote for the question before.

The questions go from easy to hard. Try each question first, then open its Answer.

Run this page on Colab

Questions#

Each question gives the header of the function to write, and examples with the value that each call returns.

# Setup for the questions below: this page needs no imports and no files.

Question 1 (easy): write a function#

Write a function called word_lengths that takes a list of strings and returns a new list with the length of each string.

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

def word_lengths(words):
    ...

Examples

word_lengths(['hello', 'world'])
[5, 5]
word_lengths(['a', 'list', 'of', 'words'])
[1, 4, 2, 5]
word_lengths([])
[]

Question 2 (easy): write a function#

Write a function called pig_latin that converts a lowercase English word to Pig Latin:

  • If the word starts with a vowel (a, e, i, o or u), add 'ay' to the end of the word.

  • If the word starts with any other letter, move the first letter to the end of the word, and then add 'ay'.

Hint: word[1:] is the word without its first letter.

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

def pig_latin(word):
    ...

Examples

pig_latin('hello')
'ellohay'
pig_latin('python')
'ythonpay'
pig_latin('apple')
'appleay'

Question 3 (easy): write a function#

Write a function called letter_grade that takes a score from 0 to 100 and returns the letter grade: 'A' for 90 or more, 'B' for 80 or more, 'C' for 70 or more, 'D' for 60 or more, and 'F' for less than 60.

Use one if, three elif branches and one else. Then answer: why must the tests be in this order? What goes wrong if the first test is score >= 60?

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

def letter_grade(score):
    ...

Examples

letter_grade(85)
'B'
letter_grade(59)
'F'
letter_grade(90)
'A'
letter_grade(100)
'A'

Question 4 (easy): write a function#

A movie ticket costs 8 dollars for a child (younger than 13), 12 dollars for an adult (13 to 64), and 8 dollars for a senior (65 or older). Write a function called movie_ticket that takes an age and returns the price.

Write it in two ways:

  • with if, elif and else;

  • with one if and one else, and the operator and in the condition.

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

def movie_ticket(age):
    ...

Examples

movie_ticket(10)
8
movie_ticket(30)
12
movie_ticket(13)
12
movie_ticket(64)
12
movie_ticket(65)
8

Question 5 (easy): write a function#

Write a function called describe_temp that takes a temperature in degrees Celsius and returns 'hot' for 30 or more, 'warm' for 20 or more, and 'cool' for 10 or more. Use if and elif, with no else branch.

Then answer: what does describe_temp(5) return, and why?

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

def describe_temp(celsius):
    ...

Examples

describe_temp(25)
'warm'
describe_temp(35)
'hot'
describe_temp(12)
'cool'

Question 6 (easy): write a function#

Write a function called max_of_three that takes three numbers and returns the largest of them. Do not use the built-in function max. Use if statements inside if statements (nested if statements), and no and or or.

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

def max_of_three(a, b, c):
    ...

Examples

max_of_three(3, 7, 5)
7
max_of_three(9, 2, 4)
9
max_of_three(1, 2, 3)
3
max_of_three(4, 4, 4)
4

Question 7 (easy): write a function#

Write a function called rotate_list that takes a list and an integer k, and returns a new list with the first k items moved to the end. Assume that k is from 0 to the length of the list.

Hint: use two slices and the + operator.

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

def rotate_list(items, k):
    ...

Examples

rotate_list([1, 2, 3, 4, 5], 2)
[3, 4, 5, 1, 2]
rotate_list(['a', 'b', 'c'], 1)
['b', 'c', 'a']
rotate_list([1, 2, 3], 0)
[1, 2, 3]

Question 8 (easy): write functions#

Write three functions for a list of numbers: my_sum returns the sum of the numbers, my_min returns the smallest number, and my_max returns the largest number. They do what the built-in functions sum, min and max do. Assume that the list is not empty. Do not use sum, min, max or sorted.

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

def my_sum(numbers):
    ...

def my_min(numbers):
    ...

def my_max(numbers):
    ...

Examples

my_sum([1, 2, 3, 4])
10
my_min([4, 2, 8, 1])
1
my_max([4, 2, 8, 1])
8
my_min([-3, 5, -10, 0])
-10

Question 9 (easy): write a function#

Write a function called cumulative_sum that takes a list of numbers and returns a new list of the running totals: item i of the result is the sum of the items from index 0 to index i.

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

def cumulative_sum(numbers):
    ...

Examples

cumulative_sum([1, 2, 3, 4])
[1, 3, 6, 10]
cumulative_sum([5, -5, 5])
[5, 0, 5]
cumulative_sum([])
[]

Question 10 (easy): write a function#

Write a function called add_lists that takes two lists of numbers with the same length, and returns a new list in which each item is the sum of the two items at the same index.

Hint: loop over the indexes with range(len(a)).

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

def add_lists(a, b):
    ...

Examples

add_lists([1, 2, 3], [10, 20, 30])
[11, 22, 33]
add_lists([0.5, 1], [0.5, -1])
[1.0, 0]

Question 11 (easy): write a function#

Write a function called remove_chars that takes two strings, text and chars, and returns a new string: text without the characters that are in chars.

Hint: x not in y is True when x in y is False.

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

def remove_chars(text, chars):
    ...

Examples

remove_chars('hello world', 'aeiou')
'hll wrld'
remove_chars('banana', 'n')
'baaa'
remove_chars('abc', 'xyz')
'abc'

Question 12 (easy): write a function#

Write a function called remove_items that takes two lists, items and bad, and returns a new list: items without the items that are in bad. Do not change the list items.

By the way: the list method remove removes only the first match, and it raises a ValueError if there is no match.

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

def remove_items(items, bad):
    ...

Examples

remove_items([1, 2, 3, 2, 4, 2], [2])
[1, 3, 4]
remove_items(['a', 'b', 'c', 'a'], ['a', 'c'])
['b']
remove_items([1, 2], [])
[1, 2]

Question 13 (easy): write a function#

Write a function called remove_duplicates that takes a list and returns a new list without duplicates. Keep the first occurrence of each item, and keep the items in their original order.

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

def remove_duplicates(lst):
    ...

Examples

remove_duplicates([1, 2, 1, 3, 2, 4])
[1, 2, 3, 4]
remove_duplicates(['b', 'a', 'b', 'b'])
['b', 'a']
remove_duplicates([])
[]

Question 14 (easy): write a function#

Write a function called my_index that takes a list and a value, and returns the index of the first occurrence of the value in the list, or -1 if the value is not in the list.

By the way: the list method index does the same, but it raises a ValueError if the value is not in the list. Here, return -1, as the string method find does. Do not use index.

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

def my_index(lst, x):
    ...

Examples

my_index([10, 20, 30], 20)
1
my_index([10, 20, 30, 20], 20)
1
my_index([10, 20, 30], 99)
-1

Question 15 (medium): write a function#

A store gives discounts with the coupon code 'SAVE10'. Write a function called final_price that takes a price, a boolean member (True for a club member), and a coupon code (a string), and returns the price after the discount:

  • a member with the coupon 'SAVE10' gets 10 percent off;

  • a person who is not a member, with the coupon 'SAVE10', gets 5 percent off;

  • without the coupon, everybody pays the full price.

Use an if/else statement inside each branch of an outer if/else statement.

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

def final_price(price, member, coupon):
    ...

Examples

final_price(100, True, 'SAVE10')
90.0
final_price(100, False, 'SAVE10')
95.0
final_price(100, True, 'HELLO')
100
final_price(100, False, '')
100

Question 16 (medium): write a function#

Write a function called triangle_type that takes the lengths of the three sides of a triangle and returns:

  • 'not a triangle' if the sides cannot make a triangle: the sum of each two sides must be greater than the third side;

  • else 'equilateral' if the three sides are equal;

  • else 'isosceles' if two sides are equal;

  • else 'scalene' (all the sides are different).

Use an if/elif/else statement inside an if statement.

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

def triangle_type(a, b, c):
    ...

Examples

triangle_type(5, 5, 5)
'equilateral'
triangle_type(5, 5, 8)
'isosceles'
triangle_type(3, 4, 5)
'scalene'
triangle_type(1, 2, 10)
'not a triangle'
triangle_type(1, 2, 3)
'not a triangle'

Question 17 (medium): write a function#

Write a function called is_leap_year that takes a year and returns True if it is a leap year and False otherwise. The rules:

  • a year that is divisible by 4 is a leap year,

  • except a year that is divisible by 100 is not a leap year,

  • except a year that is divisible by 400 is a leap year.

Use three levels of nested if/else statements. Hint: year % 4 == 0 is True if year is divisible by 4.

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

def is_leap_year(year):
    ...

Examples

is_leap_year(2024)
True
is_leap_year(2023)
False
is_leap_year(1900)
False
is_leap_year(2000)
True

Question 18 (medium): write a function#

Write a function called my_contains that takes a list and a value, and returns True if the value is in the list and False otherwise. Do what the operator in does (x in lst), but use a loop, and do not use the operator in. (The word in in a for statement, for item in lst:, is part of the for statement, not the operator in, so you can use it.)

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

def my_contains(lst, x):
    ...

Examples

my_contains([1, 2, 3], 2)
True
my_contains([1, 2, 3], 9)
False

Question 19 (medium): write a function#

Write a function called common_items that takes two lists, a and b, and returns a new list of the items that are in both lists. Do not repeat an item, and keep the items in the order in which they first occur in a. Do not use the operator in: use the function my_contains of Question 18. Use a nested loop: for each item of a, an inner loop looks at each item of b.

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

def common_items(a, b):
    ...

Examples

common_items([1, 2, 3], [2, 3, 4])
[2, 3]
common_items([3, 1, 3, 2], [2, 3, 3])
[3, 2]
common_items(['x'], ['y'])
[]

Question 20 (medium): write a function#

Write a function called my_count that takes a list and a value, and returns how many times the value occurs in the list. Do what the list method count does, but use a loop and an if statement.

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

def my_count(lst, x):
    ...

Examples

my_count([1, 2, 3, 2, 4, 2], 2)
3
my_count([1, 2, 3], 9)
0

Question 21 (medium): write a function#

Write a function called most_frequent that takes a list that is not empty, and returns the item that occurs the most times. If two or more items occur the same number of times, return the one that occurs first in the list. Use a nested loop: for each item, an inner loop counts how many times it occurs.

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

def most_frequent(lst):
    ...

Examples

most_frequent([1, 2, 1, 3, 2, 4, 2])
2
most_frequent(['b', 'a', 'a', 'b'])
'b'
most_frequent([7])
7

Question 22 (medium): write a function#

Write a function called my_reverse that takes a list and returns a new list with the items in the opposite order. Do not use the function reversed or the list method reverse.

Hint: range(START, STOP, STEP) with a negative STEP counts down.

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

def my_reverse(lst):
    ...

Examples

my_reverse([1, 2, 3])
[3, 2, 1]
my_reverse(['a'])
['a']
my_reverse([])
[]

Question 23 (medium): write a function#

Write a function called my_join that takes a list of strings and returns one string, with one space between each two strings. Do what ' '.join(words) does, but do not use join. Be careful: there is no space at the start or at the end of the result.

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

def my_join(words):
    ...

Examples

my_join(['hello', 'world'])
'hello world'
my_join(['one', 'two', 'three'])
'one two three'
my_join(['alone'])
'alone'
my_join([])
''

Question 24 (medium): write a function#

Write a function called acronym that takes a phrase (words separated by spaces, each word starting with a capital letter) and returns its acronym: the first letter of each word.

Hint: the string method split returns a list of the words of a string.

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

def acronym(phrase):
    ...

Examples

acronym('North Atlantic Treaty Organization')
'NATO'
acronym('As Soon As Possible')
'ASAP'

Question 25 (medium): write a function#

Write a function called acronyms that takes a list of phrases and returns a list of their acronyms. Use a nested loop: the outer loop goes through the phrases, and the inner loop goes through the words of one phrase.

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

def acronyms(phrases):
    ...

Examples

acronyms(['North Atlantic Treaty Organization', 'As Soon As Possible'])
['NATO', 'ASAP']
acronyms([])
[]

Question 26 (medium): write a function#

Write a function called count_vowels_words that takes a list of lowercase words and returns a list with the number of vowels (a, e, i, o, u) in each word. Use a nested loop: the outer loop goes through the list, and the inner loop goes through the letters of one word.

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

def count_vowels_words(words):
    ...

Examples

count_vowels_words(['hello', 'sky', 'aeiou'])
[2, 0, 5]
count_vowels_words(['banana'])
[3]

Question 27 (medium): write a function#

Write a function called multiplication_table that takes a positive integer n and returns the multiplication table from 1 to n as a list of n lists: row i (counting from 1) holds i * 1, i * 2, …, i * n.

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

def multiplication_table(n):
    ...

Examples

multiplication_table(3)
[[1, 2, 3], [2, 4, 6], [3, 6, 9]]
multiplication_table(1)
[[1]]
multiplication_table(4)
[[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12], [4, 8, 12, 16]]

Question 28 (medium): write a function#

A grid is a list of rows, and each row is a list of numbers. Write a function called add_grids that takes two grids with the same number of rows and the same number of columns, and returns a new grid in which each number is the sum of the two numbers at the same place. Use a nested loop.

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

def add_grids(a, b):
    ...

Examples

add_grids([[1, 2], [3, 4]], [[10, 20], [30, 40]])
[[11, 22], [33, 44]]
add_grids([[1, 2, 3]], [[1, 1, 1]])
[[2, 3, 4]]

Question 29 (medium): write a function#

Write a function called all_pairs that takes a list and returns a list of all the pairs of its items. Each pair is a list of two items, [lst[i], lst[j]], with i less than j.

Hint: the inner loop starts at the index after the index of the outer loop.

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

def all_pairs(lst):
    ...

Examples

all_pairs([1, 2, 3])
[[1, 2], [1, 3], [2, 3]]
all_pairs(['a', 'b', 'c', 'd'])
[['a', 'b'], ['a', 'c'], ['a', 'd'], ['b', 'c'], ['b', 'd'], ['c', 'd']]
all_pairs([1])
[]

Question 30 (medium): write a function#

Write a function called has_duplicates that takes a list and returns True if a value occurs more than once in the list, and False otherwise. Use a nested loop that compares each pair of indexes i and j, with i less than j.

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

def has_duplicates(lst):
    ...

Examples

has_duplicates([1, 2, 3, 2])
True
has_duplicates([1, 2, 3])
False
has_duplicates([])
False

Question 31 (medium): write a function#

Write a function called find_duplicates that takes a list and returns a new list of the values that occur more than once. List each value once, in the order of its first occurrence in the list.

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

def find_duplicates(lst):
    ...

Examples

find_duplicates([1, 2, 1, 3, 2, 1])
[1, 2]
find_duplicates([2, 1, 1, 2])
[2, 1]
find_duplicates([1, 2, 3])
[]

Question 32 (medium): write a function#

Write a function called my_split that takes a string and returns a list of its words. The words are separated by one or more spaces, and the string can start or end with spaces. Do what s.split() does, but do not use split.

Hint: build each word one character at a time. When you get to a space, the word (if there is one) is complete.

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

def my_split(s):
    ...

Examples

my_split('hello world')
['hello', 'world']
my_split('  too   many   spaces  ')
['too', 'many', 'spaces']
my_split('')
[]
my_split('   ')
[]

Question 33 (hard): write a function#

Write a function called my_find that takes two strings, s and sub, and returns the index in s where sub occurs for the first time, or -1 if sub does not occur in s. Do what the string method find does, but do not use find, index or in. Assume that sub is not empty.

Use a nested loop: the outer loop tries each start index i in s; the inner loop compares the characters of sub with the characters of s from index i, one at a time.

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

def my_find(s, sub):
    ...

Examples

my_find('hello', 'll')
2
my_find('banana', 'na')
2
my_find('hello', 'z')
-1
my_find('hi', 'high')
-1

Question 34 (hard): write a function#

Write a function called find_all that takes s and sub and returns a list of all the indexes where sub starts in s.

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

def find_all(s, sub):
    ...

Examples

find_all('hello', 'l')
[2, 3]
find_all('banana', 'ana')
[1, 3]
find_all('hello', 'z')
[]

Question 35 (hard): write a function#

Write a function called my_replace that takes three strings, s, old and new, and returns a new string in which each occurrence of old is replaced by new. Do what s.replace(old, new) does, but do not use replace. Assume that old is not empty.

Read s from left to right. After a match, continue after the end of the match: in 'aaa', 'aa' matches at index 0, and the next match can start only at index 2. So my_replace('aaa', 'aa', 'b') returns 'ba', as 'aaa'.replace('aa', 'b') does.

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

def my_replace(s, old, new):
    ...

Examples

my_replace('hello', 'l', 'L')
'heLLo'
my_replace('banana', 'an', 'AN')
'bANANa'
my_replace('aaa', 'aa', 'b')
'ba'
my_replace('hello', 'x', 'y')
'hello'

Question 36 (hard): write a function#

Write a function called my_strip that takes a string and returns it without the spaces at the start and at the end. Do what s.strip() does for spaces, but do not use strip.

Hint: with a loop, find the index of the first character that is not a space, and the index of the last one. Then return one slice.

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

def my_strip(s):
    ...

Examples

my_strip('   hello   ')
'hello'
my_strip('  two words ')
'two words'
my_strip('   ')
''
my_strip('x')
'x'

Question 37 (hard): write a function#

Write a function called sort_list that sorts a list of numbers from the smallest to the largest. Do not use the function sorted or the list method sort. Change the list itself, and return it too.

Use a nested loop: for each index i, compare lst[i] with each item after it, lst[j]. If lst[j] is smaller, swap the two items. When the inner loop is done, lst[i] holds the smallest item of lst[i:].

To swap two items, use a temporary variable:

temp = lst[i]
lst[i] = lst[j]
lst[j] = temp

Then answer: how would you change the function so that it returns a new sorted list and does not change the list that it gets?

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

def sort_list(lst):
    ...

Examples

sort_list([4, 2, 8, 1])
[1, 2, 4, 8]
sort_list([3, 1, 2, 1])
[1, 1, 2, 3]
numbers = [5, 4, 3]
sort_list(numbers)
numbers
[3, 4, 5]

Question 38 (hard): write a function#

Write a function called count_items that takes a list of strings and returns a list of pairs [item, count]: one pair for each different item, in sorted order, with the number of times the item occurs in the list.

Hint: first make a list of the different items (Question 13), and sort it with sorted. Then, for each item, count how many times it occurs, with an inner loop.

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

def count_items(lst):
    ...

Examples

count_items(['c', 'a', 'a', 'b', 'c', 'a'])
[['a', 3], ['b', 1], ['c', 2]]
count_items(['to', 'be', 'or', 'not', 'to', 'be'])
[['be', 2], ['not', 1], ['or', 1], ['to', 2]]
count_items([])
[]

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