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.
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([])
[]
Answer
def word_lengths(words):
result = []
for w in words:
result.append(len(w))
return result
Then try: word_lengths(['hello', 'world']).
This is the accumulator pattern with a list: start with an empty list, and append one value in each pass of the loop. For an empty list, the loop does not run, and the function returns [].
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,ooru), 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'
Answer
def pig_latin(word):
if word[0] in 'aeiou':
return word + 'ay'
else:
return word[1:] + word[0] + 'ay'
Then try: pig_latin('hello').
word[0] in 'aeiou' is True if the first letter is one of the characters of the string 'aeiou'. word[1:] is a slice: all the characters from index 1 to the end. The else: is not necessary, because return ends the function:
def pig_latin(word):
if word[0] in 'aeiou':
return word + 'ay'
return word[1:] + word[0] + 'ay'
By the way: these are simplified rules. In real Pig Latin, all the consonants before the first vowel move to the end ('string' becomes 'ingstray').
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'
Answer
def letter_grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
Then try: letter_grade(85).
Python tests the conditions from the top down, and runs only the first branch whose condition is True. So the elif score >= 80 branch runs only when score >= 90 is False: the score is 80 or more, and less than 90.
If the first test were score >= 60, a score of 95 would make it True, and the function would return 'D'. The other tests would never run for any score of 60 or more.
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,elifandelse;with one
ifand oneelse, and the operatorandin 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
Answer
Solution 1 (if, elif, else):
def movie_ticket(age):
if age < 13:
return 8
elif age < 65:
return 12
else:
return 8
Then try: movie_ticket(10).
The elif branch runs only when age < 13 is False, so it does not have to test age >= 13 again.
Solution 2 (and):
def movie_ticket(age):
if age >= 13 and age <= 64:
return 12
else:
return 8
A and B is True only if both A and B are True. Children and seniors pay the same price, so one test for adults is enough.
Test the ages at the edges (12, 13, 64, 65): most mistakes (< in place of <=) show there.
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'
Answer
def describe_temp(celsius):
if celsius >= 30:
return 'hot'
elif celsius >= 20:
return 'warm'
elif celsius >= 10:
return 'cool'
Then try: describe_temp(25).
describe_temp(5) returns None. For 5, no condition is True, so no return statement runs. A function that ends without a return statement returns None. In a notebook cell, describe_temp(5) shows nothing; print(describe_temp(5)) displays None.
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
Answer
def max_of_three(a, b, c):
if a >= b:
if a >= c:
return a
else:
return c
else:
if b >= c:
return b
else:
return c
Then try: max_of_three(3, 7, 5).
The outer if finds the larger of a and b. Each inner if compares that one with c. There are four paths through the code, and each one ends with a return. To test the function, use one example for each path.
Without the restriction on and, it is shorter:
def max_of_three(a, b, c):
if a >= b and a >= c:
return a
elif b >= c:
return b
else:
return c
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]
Answer
def rotate_list(items, k):
return items[k:] + items[:k]
Then try: rotate_list([1, 2, 3, 4, 5], 2).
items[k:] is the items from index k to the end, and items[:k] is the first k items. + puts two lists together in a new list. A slice also makes a new list, so the function does not change the list that it gets.
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
Answer
def my_sum(numbers):
total = 0
for n in numbers:
total = total + n
return total
def my_min(numbers):
smallest = numbers[0]
for n in numbers:
if n < smallest:
smallest = n
return smallest
def my_max(numbers):
biggest = numbers[0]
for n in numbers:
if n > biggest:
biggest = n
return biggest
Then try: my_sum([1, 2, 3, 4]).
Each function uses a variable that holds the result so far. my_min and my_max start with the first item, not with 0: for [-3, 5, -10, 0], a my_max that starts with 0 works by chance, but a my_min that starts with 0 is wrong for a list of positive numbers such as [4, 2, 8].
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([])
[]
Answer
def cumulative_sum(numbers):
total = 0
result = []
for n in numbers:
total = total + n
result.append(total)
return result
Then try: cumulative_sum([1, 2, 3, 4]).
The function has two accumulators: total (a number) and result (a list). After the loop adds each number to total, it appends the new total to result.
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]
Answer
def add_lists(a, b):
result = []
for i in range(len(a)):
result.append(a[i] + b[i])
return result
Then try: add_lists([1, 2, 3], [10, 20, 30]).
A loop such as for x in a: gives the items of one list only. To get the items of two lists at the same index, loop over the indexes, and use a[i] and b[i].
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'
Answer
Solution 1 (build a new string, one character at a time):
def remove_chars(text, chars):
result = ''
for ch in text:
if ch not in chars:
result = result + ch
return result
Then try: remove_chars('hello world', 'aeiou').
Solution 2 (the string method replace, once for each character to remove):
def remove_chars(text, chars):
for ch in chars:
text = text.replace(ch, '')
return text
text.replace(ch, '') returns a new string without any ch. It removes one character (or one substring) each time, so Solution 2 calls it once for each character of chars. Strings are immutable: replace does not change text, so the loop assigns the new string to text again.
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]
Answer
def remove_items(items, bad):
result = []
for x in items:
if x not in bad:
result.append(x)
return result
Then try: remove_items([1, 2, 3, 2, 4, 2], [2]).
The function makes a new list, and does not change items. A function that changes a list that it gets as an argument also changes the caller’s list, because the parameter and the caller’s variable refer to the same list (aliasing). That is not always wrong, but the caller must expect it.
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([])
[]
Answer
def remove_duplicates(lst):
result = []
for x in lst:
if x not in result:
result.append(x)
return result
Then try: remove_duplicates([1, 2, 1, 3, 2, 4]).
The test x not in result looks in the list that the loop builds: an item that is already in result is not added again.
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
Answer
def my_index(lst, x):
for i in range(len(lst)):
if lst[i] == x:
return i
return -1
Then try: my_index([10, 20, 30], 20).
The function needs the index, not only the item, so it loops over range(len(lst)). The return i in the loop ends the function at the first match. The return -1 is after the loop: it runs only if no item matched.
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
Answer
def final_price(price, member, coupon):
if member:
if coupon == 'SAVE10':
return price * 0.9
else:
return price
else:
if coupon == 'SAVE10':
return price * 0.95
else:
return price
Then try: final_price(100, True, 'SAVE10').
member is a boolean, so if member: is enough (if member == True: gives the same result). There are four cases, one for each path through the code. Note that 100 * 0.9 is the float 90.0, but the full price is the integer 100.
The outer test can also be the coupon:
def final_price(price, member, coupon):
if coupon == 'SAVE10':
if member:
return price * 0.9
else:
return price * 0.95
else:
return price
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'
Answer
def triangle_type(a, b, c):
if a + b > c and a + c > b and b + c > a:
if a == b and b == c:
return 'equilateral'
elif a == b or b == c or a == c:
return 'isosceles'
else:
return 'scalene'
else:
return 'not a triangle'
Then try: triangle_type(5, 5, 5).
The test for 'equilateral' comes before the test for 'isosceles'. If the order were different, triangle_type(5, 5, 5) would return 'isosceles', because a == b is True.
The sides 1, 2, 3 are not a triangle: 1 + 2 > 3 is False.
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
Answer
def is_leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
Then try: is_leap_year(2024).
Each exception is one level deeper than the rule that it changes. The four examples test the four paths.
With and and or, one expression is enough:
def is_leap_year(year):
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
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
Answer
def my_contains(lst, x):
for item in lst:
if item == x:
return True
return False
Then try: my_contains([1, 2, 3], 2).
The return True in the loop ends the function at the first match. The return False must be after the loop, not in an else: in the loop: an else: return False would end the function after the first item.
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'])
[]
Answer
Solution 1 (a nested loop):
def my_contains(lst, x):
for item in lst:
if item == x:
return True
return False
def common_items(a, b):
result = []
for x in a:
for y in b:
if x == y and not my_contains(result, x):
result.append(x)
return result
Then try: common_items([1, 2, 3], [2, 3, 4]).
The inner loop finds the items that are in both lists. not my_contains(result, x) makes sure that an item is added only once.
Solution 2 (call the function of Question 18 in place of the inner loop too):
def my_contains(lst, x):
for item in lst:
if item == x:
return True
return False
def common_items(a, b):
result = []
for x in a:
if my_contains(b, x) and not my_contains(result, x):
result.append(x)
return result
Solution 2 still does a nested loop: my_contains has a loop, and Solution 2 calls it in a loop. A function that you already wrote makes the new function shorter and easier to read.
(The blocks repeat my_contains from Question 18, so that you can run each block on its own.)
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
Answer
def my_count(lst, x):
count = 0
for item in lst:
if item == x:
count = count + 1
return count
Then try: my_count([1, 2, 3, 2, 4, 2], 2).
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
Answer
Solution 1 (a nested loop):
def most_frequent(lst):
best = lst[0]
best_count = 0
for x in lst:
count = 0
for y in lst:
if y == x:
count = count + 1
if count > best_count:
best_count = count
best = x
return best
Then try: most_frequent([1, 2, 1, 3, 2, 4, 2]).
The inner loop is the loop of Question 20. The > (not >=) keeps the first item when two items have the same count: for ['b', 'a', 'a', 'b'], 'a' has the count 2, the same as 'b', so best stays 'b'.
Solution 2 (call the function of Question 20):
def my_count(lst, x):
count = 0
for item in lst:
if item == x:
count = count + 1
return count
def most_frequent(lst):
best = lst[0]
for x in lst:
if my_count(lst, x) > my_count(lst, best):
best = x
return best
(The blocks repeat my_count from Question 20, so that you can run each block on its own.)
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([])
[]
Answer
Solution 1 (count the indexes down):
def my_reverse(lst):
result = []
for i in range(len(lst) - 1, -1, -1):
result.append(lst[i])
return result
Then try: my_reverse([1, 2, 3]).
range(len(lst) - 1, -1, -1) gives the indexes from the last index down to 0. The STOP value is -1, because range stops before STOP.
Solution 2 (put each item in front):
def my_reverse(lst):
result = []
for x in lst:
result = [x] + result
return result
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([])
''
Answer
Solution 1 (a space before each word, except the first):
def my_join(words):
result = ''
for i in range(len(words)):
if i > 0:
result = result + ' '
result = result + words[i]
return result
Then try: my_join(['hello', 'world']).
Solution 2 (start with the first word, then add a space and each later word):
def my_join(words):
if len(words) == 0:
return ''
result = words[0]
for w in words[1:]:
result = result + ' ' + w
return result
words[1:] is the list without its first item. The if at the start is necessary: for an empty list, words[0] is an IndexError.
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'
Answer
def acronym(phrase):
result = ''
for w in phrase.split():
result = result + w[0]
return result
Then try: acronym('North Atlantic Treaty Organization').
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([])
[]
Answer
Solution 1 (a nested loop):
def acronyms(phrases):
result = []
for phrase in phrases:
short = ''
for w in phrase.split():
short = short + w[0]
result.append(short)
return result
Then try: acronyms(['North Atlantic Treaty Organization', 'As Soon As Possible']).
short must start again as '' for each phrase, so short = '' is inside the outer loop. If it were before the outer loop, the second acronym would be 'NATOASAP'.
Solution 2 (call the function of Question 24):
def acronym(phrase):
result = ''
for w in phrase.split():
result = result + w[0]
return result
def acronyms(phrases):
result = []
for phrase in phrases:
result.append(acronym(phrase))
return result
(The blocks repeat acronym from Question 24, so that you can run each block on its own.)
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]
Answer
def count_vowels_words(words):
result = []
for w in words:
count = 0
for ch in w:
if ch in 'aeiou':
count = count + 1
result.append(count)
return result
Then try: count_vowels_words(['hello', 'sky', 'aeiou']).
The outer loop goes through a list; the inner loop goes through a string. count = 0 is inside the outer loop, so each word starts with a count of 0. The append is after the inner loop, so it runs once for each word.
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]]
Answer
def multiplication_table(n):
table = []
for i in range(1, n + 1):
row = []
for j in range(1, n + 1):
row.append(i * j)
table.append(row)
return table
Then try: multiplication_table(3).
The inner loop makes one row. row = [] is inside the outer loop, so each row is a new list. range(1, n + 1) gives 1, 2, ..., n: range stops before STOP.
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]]
Answer
def add_grids(a, b):
result = []
for i in range(len(a)):
row = []
for j in range(len(a[i])):
row.append(a[i][j] + b[i][j])
result.append(row)
return result
Then try: add_grids([[1, 2], [3, 4]], [[10, 20], [30, 40]]).
a[i] is row i of the grid (a list), and a[i][j] is item j of that row. This is Question 10 (add_lists) for each row. So, if you wrote add_lists, this solution is shorter:
def add_lists(a, b):
result = []
for i in range(len(a)):
result.append(a[i] + b[i])
return result
def add_grids(a, b):
result = []
for i in range(len(a)):
result.append(add_lists(a[i], b[i]))
return result
(The blocks repeat add_lists from Question 10, so that you can run each block on its own.)
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])
[]
Answer
def all_pairs(lst):
result = []
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
result.append([lst[i], lst[j]])
return result
Then try: all_pairs([1, 2, 3]).
Because j starts at i + 1, each pair occurs once ([1, 2] but not [2, 1]), and no item makes a pair with itself. For a list with one item, the inner loop never runs, so the result is [].
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
Answer
def has_duplicates(lst):
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
if lst[i] == lst[j]:
return True
return False
Then try: has_duplicates([1, 2, 3, 2]).
The loops are the loops of Question 29 (all_pairs). The function returns True at the first pair of equal items.
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])
[]
Answer
def find_duplicates(lst):
result = []
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
if lst[i] == lst[j] and lst[i] not in result:
result.append(lst[i])
return result
Then try: find_duplicates([1, 2, 1, 3, 2, 1]).
The outer loop goes through the items in their order in the list, so the values come in the order of their first occurrence: for [2, 1, 1, 2] the result is [2, 1], though the first repeated item in the list is 1 (index 2). The test lst[i] not in result makes sure that a value that occurs three times is in the result only once.
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(' ')
[]
Answer
def my_split(s):
words = []
word = ''
for ch in s:
if ch == ' ':
if word != '':
words.append(word)
word = ''
else:
word = word + ch
if word != '':
words.append(word)
return words
Then try: my_split('hello world').
word holds the letters of the current word. At a space, the function appends the word to the list, but only if the word is not empty: that is how it ignores two spaces in a row. The last word has no space after it, so the if after the loop appends it.
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
Answer
def my_find(s, sub):
for i in range(len(s) - len(sub) + 1):
match = True
for j in range(len(sub)):
if s[i + j] != sub[j]:
match = False
if match:
return i
return -1
Then try: my_find('hello', 'll').
The last possible start index is len(s) - len(sub): at a larger index, there are not enough characters left in s. So the outer loop uses range(len(s) - len(sub) + 1). If sub is longer than s, that range is empty, and the function returns -1.
match starts as True for each start index, and becomes False if one character is different.
With a slice in place of the inner loop, the function is shorter:
def my_find(s, sub):
for i in range(len(s) - len(sub) + 1):
if s[i:i + len(sub)] == sub:
return i
return -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')
[]
Answer
def find_all(s, sub):
result = []
for i in range(len(s) - len(sub) + 1):
if s[i:i + len(sub)] == sub:
result.append(i)
return result
Then try: find_all('hello', 'l').
It is the loop of Question 33, but it appends each index to a list, and does not stop at the first match. Matches can overlap: in 'banana', 'ana' starts at index 1 and at index 3.
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'
Answer
Solution 1 (count the characters to skip after a match):
def my_replace(s, old, new):
m = len(old)
result = ''
skip = 0
for i in range(len(s)):
if skip > 0:
skip = skip - 1
elif s[i:i + m] == old:
result = result + new
skip = m - 1
else:
result = result + s[i]
return result
Then try: my_replace('hello', 'l', 'L').
A for loop moves one index at a time. After a match at index i, the characters at indexes i + 1 to i + m - 1 are part of the match, so the next m - 1 passes of the loop do nothing (skip). At the end of the string, the slice s[i:i + m] is shorter than m characters, so it does not match.
Solution 2 (split and join):
def my_replace(s, old, new):
return new.join(s.split(old))
s.split(old) returns the parts of s between the occurrences of old, and new.join(...) puts the parts together again with new between them.
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'
Answer
def my_strip(s):
start = -1
end = -1
for i in range(len(s)):
if s[i] != ' ':
if start == -1:
start = i
end = i
if start == -1:
return ''
return s[start:end + 1]
Then try: my_strip(' hello ').
start gets the index of the first character that is not a space: only once, while start is still -1. end gets the index of each character that is not a space, so after the loop it is the index of the last one. If the string has only spaces, start stays -1, and the function returns ''. The slice is s[start:end + 1], because a slice stops before its second index.
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]
Answer
Solution 1 (swap each time a later item is smaller):
def sort_list(lst):
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
if lst[j] < lst[i]:
temp = lst[i]
lst[i] = lst[j]
lst[j] = temp
return lst
Then try: sort_list([4, 2, 8, 1]).
Solution 2 (selection sort: find the index of the smallest item, then swap only once):
def sort_list(lst):
for i in range(len(lst)):
smallest = i
for j in range(i + 1, len(lst)):
if lst[j] < lst[smallest]:
smallest = j
temp = lst[i]
lst[i] = lst[smallest]
lst[smallest] = temp
return lst
Both functions change the list that they get. In the third example, numbers and lst refer to the same list, so after the call, numbers is sorted too.
To return a new list, sort a copy: start the function with lst = lst[:] (a slice of the whole list is a new list). Then the caller’s list does not change.
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([])
[]
Answer
def count_items(lst):
uniques = []
for x in lst:
if x not in uniques:
uniques.append(x)
result = []
for x in sorted(uniques):
count = 0
for y in lst:
if y == x:
count = count + 1
result.append([x, count])
return result
Then try: count_items(['c', 'a', 'a', 'b', 'c', 'a']).
The first loop makes the list of different items. sorted returns a new sorted list, and does not change uniques. The nested loop is the loop of Question 20 (my_count) for each item.
If you wrote my_count (Question 20), call it in place of the inner loop:
def my_count(lst, x):
count = 0
for item in lst:
if item == x:
count = count + 1
return count
def count_items(lst):
uniques = []
for x in lst:
if x not in uniques:
uniques.append(x)
result = []
for x in sorted(uniques):
result.append([x, my_count(lst, x)])
return result
By the way: a dictionary (Chapter 10) does this job with one loop.
(The blocks repeat my_count from Question 20, so that you can run each block on its own.)
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