This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 5: Applied problem solving

Suffixes

face Josiah Wang

I think you probably had enough of dealing with list of numbers. As a final challenge, let us deal with list of strings instead!

Write a function named add_suffixes() that appends a list of suffixes to the end of each string in another list. The function takes two input arguments: the first is a list called words, the second is a list called suffixes. The function should return a nested list, containing all strings in words appended to each suffix in suffixes.

For example, add_suffixes(["play", "laugh", "extend"], ["ing", "ed"]) should return [["playing", "laughing", "extending"], ["played", "laughed", "extended"]].

Remember to test your function as usual to ensure that it’s behaving as you expected!

Reading from text files

Let us also use this exercise to learn how to read text from a file in Python! (We will do more of this in more detail in future lessons)

First, download the following two files verbs1.txt and verbs2.txt.

Save the files in the same directory as your script. Examine the content of the files. You should see a list of verbs per line in each file.

The following function reads in the contents of the text file, line by line. I think the code should be pretty intuitive. For each line in the file, it first removes any extra spaces and "\n" from the beginning and end of each line with line.strip() (Line 5). It then appends the line to the list verbs (Line 6). You should end up with a list of verbs.

1
2
3
4
5
6
7
8
9
def load_verbs_from_file(filename):
    verbs = []
    textfile = open(filename)
    for line in textfile:
        verb = line.strip()  # strips off the "\n" at the end of each line
        verbs.append(verb)
    return verbs

verbs = load_verbs_from_file("verbs1.txt")

Now, write a program that reads verbs from either of these files (you can hard code the file name in your script), and add the suffixes -ing and -ed to each of these verbs. Your program should then print out the list of verbs with the suffixes.

Sample run #1 (verb1.txt)

drowning
frightening
crashing
granting
wanting
drowned
frightened
crashed
granted
wanted

Sample run #2 (verb2.txt)

disappearing
interviewing
starting
turning
opening
disappeared
interviewed
started
turned
opened