Exercises for Lesson 20

Back to Lesson 20

Exercise 1: Sorting objects

Part a: Writing a function to get the sort key

Consider a list of (firstName,lastName) tuples, like the following:

people=[("Alyssa","Hacker"),
        ("Miyeon","Lee"),
        ("Isabel", "Torres"),
        ("Ben","Bitdiddle"),
        ("Ming","Chen")]

We can write a function to take one of these tuples and return either the first or last name, enabling us to sort the list by first or last name accordingly. Write the functions and modify the calls to sort to use them.

def getFirstName(nameTuple):
    """
    Returns the first name from a (firstName,lastName) tuple.
    """
    return None # TODO: replace this!

def getLastName(nameTuple):
    """
    Returns the last name from a (firstName,lastName) tuple.
    """
    return None # TODO: replace this!

people=[("Alyssa","Hacker"),
        ("Ben","Bitdiddle"),
        ("Isabel", "Torres"),
        ("Ming","Chen"),
        ("Miyeon","Lee")]

print(people) # see what it looks like before sorting
people.sort() # TODO: change to sort by first name
print(people) # see what it looks like after sorting
people.sort() # TODO: change to sort by last name
print(people) # see what it looks like after sorting

Part b: Using an existing function to get the sort key

Consider a nested list of Point objects. To sort the list first by x coordinate and then by y coordinate, we can provide a function as a parameter to the sort function call to tell it to do this.

Fill in the function in the following program and use it to sort the list.

from graphics import *

def getKey(point):
    return None # TODO: replace this!

def main():
    mylist = [Point(1,2), Point(4,2), Point(1,0)]

    for point in mylist:
        print(point)

    mylist.sort() # TODO: use our getKey function

    for point in mylist:
        print(point)

if __name__ == "__main__":
    main()

That was cool, but what if we just want to sort by y-coordinate? What function will take a Point and return just the y-coordinate?

Try changing the code to use this already-existing function instead of one we write.

Back to Lesson 20

Exercise 2: Inheritance and method calls

The following program defines four classes. Draw a class diagram indicating the relationship between classes, as well as each class’s newly introduced instance variables, constructor, and other methods.

class A:
    def __init__(self, val):
        self.value = val # not a bug -- these don't have to match!

    def doTheThing(self):
        print("In A:", self.value)

class B(A):
    def __init__(self, value):
        A.__init__(self, value) # call the parent constructor to set self.value

class C(B):
    def __init__(self, v, otherVal):
        B.__init__(self, v) # call the parent, which eventually sets self.value

        self.otherVal = otherVal

    def doTheThing(self):
        print("In C:", self.otherVal * self.value)

class D(B):
    def __init__(self, value):
        self.value = value * 2 # just set self.value ourselves

def main():
    a = A(4)
    b = B(22)
    c = C(10, 7)
    d = D(55.505)

    for obj in [a,b,c,d]:
        obj.doTheThing()

if __name__ == "__main__":
    main()

Back to Lesson 20

Exercise 3: Using a lambda function to get the sort key

Often when we’re sorting and want to use a specific value to sort on, we may write a function for use in a single line of code. It’d be nice not to have it hanging around after. We can use the lambda keyword to create an unnamed (a.k.a. anonymous) function that we use only in the call to sort.

from graphics import *

def main():
    mylist = [Point(1,2), Point(4,2), Point(1,0)]

    for point in mylist:
        print(point)

    # TODO - change the following two lines to create a lambda function and use it
    keyFunc = None
    mylist.sort()

    for point in mylist:
        print(point)

if __name__ == "__main__":
    main()

Back to Lesson 20