Not logged in. Login

Exercise 8

Working with Lists

Create these functions in list_functions.py.

Write 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.

Create a function even_only that takes a list of numbers 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] and 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.

Lists of Objects

For this question, you need the provided person module saved in the same folder as the sorting_people.py file you'll create.

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 that asks the user for some number of people's names. It should build a list of Person objects in a 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.

Submitting

Submit all of your work through CourSys.

Updated Thu June 27 2024, 14:27 by ggbaker.