Exercises for Lesson 19

Back to Lesson 19

Exercise 1: List operations

We’ve seen some list operations before. Let’s explore a few more.

Predict the values of numbers and words after executing each of the following statements. Assume that numbers and words are reset to their original values before each statement.

numbers = [3, 1, 4, 1, 5]
words = ["apple", "banana", "cat", "dog", "elephant"]

a) "apple" in words

b) "nana" in words

c) numbers.remove(2)

d) numbers.sort()

e) words.sort(reverse=True)

f) numbers.append([words.index("cat")])

g) words.pop(numbers.pop(3))

h) words.insert(numbers[0], "fish")

Back to Lesson 19

Exercise 2: The Activity class

We want to write an Activity class to represent the things we might do on the weekend. An Activity should have the following instance variables:

  • name
  • duration

Additionally, we want the following methods:

  • getName()
  • getDuration()

part a: Write the class

Complete the class definition.

class Activity:
    pass # TODO

Back to Lesson 19

part b: Read in activities from a file

Now that we can create an Activity object, let’s add a function that reads them in from a file.

Here is an example file:

clean room,2
cook meals,3
do homework,3
hang out with friends,3
eat,1.5
eat,1.5
eat,1.5
eat,1.5

Let’s write a function that reads in a file given its name as filename (a string), and returns a list of Activity objects. To help with that, we’ll also have a function that takes a comma-separated list of strings and returns an Activity object.

def buildActivity(vals):
    """
    Builds and returns an Activity object based on vals, a list of strings.

    vals: [name, duration] as strings
    """
    return None # TODO

def parseActivitiesFromFile(filename):
    """
    Reads in activity information from the file pointed to by filename,
    and returns a list of Activity objects.
    """
    # Open the file
    # Initialize the list to store the activities in
    # For each line in the file
        # Parse the line to an Activity object and add it to the list
    # Close the file
    # Return the list of Activity objects
    return [] # TODO

Back to Lesson 19

part c: String representations

We can create a method to build a string representation of our Activity class. This method gets called when str() is used on an Activity object. As one of the special methods used with classes in Python, its name begins and ends with two underscores: __str__.

class Activity:
    ...

    def __str__(self):
        """
        Returns the string representation of this Activity.
        """
        return "" # TODO

Now we can print out the activities!

def main():
    # The file has lines "name,duration", but it doesn't *have* to
    # have .csv as the extension.  Any old text file is fine.
    activities = parseActivitiesFromFile("activites.txt")

    # Print out the activities
    for activity in activities:
        print(activity) # calls Activity.__str__(activity)

Back to Lesson 19