CMPT 120 Lab 8

This site applies only to CMPT 120 D1 (Burnaby) in Summer 2011. See the other instructors' pages for other sections.

  1. Create a function squares(n) that returns a list of all the perfect squares from 1 to n2. So, squares(5) should build the list [1, 4, 9, 16, 25], and return it. In your function, start with an empty list ([]) and use the .append method in a loop to add successive squares to the list.
  2. Create a function even_only that takes a list as an argument. It should return a list that consists of all the elements from the argument that are even numbers. For example, even_only([2,4,5,9,10,12]) should return [2, 4, 10, 12]; even_only(squares(10)) should return [4, 16, 36, 64, 100].

    Suggestion: Create an empty list for the result. Iterate though the items in the argument list. As you go, if an item is even, add it to the result list. At the end, return the result list.

  3. For this question, you will need the provided person module. Save it in the same directory as the Python file you create for this question. You can ignore the contents of this file; it just has to be there.

    After importing the person module, you will be able to create a Person object like this: person.Person("Smith", "John"), where the two arguments are the person's last and first names. For example,

    import person
    p = person.Person("Smith", "John")
    print p

    Use this class to create a program like this. It should build a list of Person objects in a for loop, sort it (with the list's .sort method), and then print the people out by going through the sorted list.

    How many people? 3

    First name: Apu
    Last name: Nahasapeemapetilon

    First name: Montgomery
    Last name: Burns

    First name: Agnes
    Last name: Skinner

    Here they are in order:
    Burns, Montgomery
    Nahasapeemapetilon, Apu
    Skinner, Agnes

    If you print a Person object, it will be printed in the “lastname, firstname” format you need. You can also extract the last and first name with the lastname() and firstname() methods.