Exercises for 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")
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
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.
Input:
- vals: [name, duration] as strings
Returns: an instance of the Activity class
"""
return None # TODO
def parseActivitiesFromFile(filename):
"""
Reads in activity information from the file pointed to by filename,
and returns a list of Activity objects.
"""
# Initialize the list to store the activities in
# Open the file
# For each line in the file
# Parse the line to an Activity object and add it to the list
# Return the list of Activity objects
return [] # TODO
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. Remember that 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.
Example: "clean room (2 hours)"
"""
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("activities.txt")
# Print out the activities
for activity in activities:
print(activity) # calls Activity.__str__(activity)
part d: Another special method
We can create a method to allow us to add two Activity
objects together, getting a composite Activity
in return. This is another special method, so its name also begins and ends with two underscores: __add__
. It is called when adding two Activity
objects with +
.
class Activity:
...
def __add__(self, other):
"""
Returns the combination of this Activity with another.
The new Activity has:
- name: concatenatation of both the names with ',' in between
- duration: the sum of the two durations
"""
return Activity("", 0) # TODO: replace with your code
Now we can combine 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("activities.txt")
# Print out the activities
for activity in activities:
print(activity) # calls Activity.__str__(activity)
# Add some together
if len(activities) >= 3:
a1 = activities[0]
a2 = activities[1]
a3 = activities[2]
print(a1 + a2 + a3) # calls Activity.__add__(a1, a2) first