Exercises for Lesson 20

Back to Lesson 20

Exercise 1: Sorting objects

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.

Part a: Writing a function to get the sort key

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

from graphics import *

def getKey(point):
    return None # TODO

def main():
    mylist = [Point(1,2), Point(4,2), Point(1,0)]
    mylist.sort() # TODO - change this line

    for point in mylist:
        print(point)

if __name__ == "__main__":
    main()

Part b: Using a lambda function to get the sort key

We only need this function for use in a single line of code, so it might be nice not to have it hanging around after. We can use the lambda keyword to create an unnamed 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