Not logged in. Login

Exercise 10

Write all of the functions required for this week in lab10.py.

Removing List Items

Suppose you want to write a program that removes the given items from the list. The program should work with two lists, like these:

targetlist = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
removelist = [2, 5, 7]

The idea is to take the targetlist and delete the elements from positions listed in removelist. So, in the first example, we want to remove elements 2, 5, and 7 from targetlist. After this it should be [0, 10, 30, 40, 60, 80, 90].

My first thought about how to do this didn't work:

def remove_positions(targetlist, removelist):
    for elt in removelist:
        del targetlist[elt]

values1 = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
positions1 = [2, 7, 5]
remove_positions(values1, positions1)
print(values1)
# at the moment, this prints: [0, 10, 30, 40, 50, 70, 90]
# should be [0, 10, 30, 40, 60, 80, 90]

values2 = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
positions2 = [1, 4, 3]
remove_positions(values2, positions2)
print(values2)
# should be [0.0, 0.2, 0.5, 0.6]

In your lab10.py, add a comment that describes why the function above doesn't work: it loops over the items in removelist and deletes each one. Why doesn't that remove the correct items?

Then fix the function so it removes the correct items. Please remove the outside-the-function test code before submitting: include only the corrected function definition and the comment.

Searching, but more

The search algorithms we have seen only return one of the positions of a value in the list. It's possible that a particular value will occur multiple times. In some cases, you want all of the occurrences returned.

In lab10.py, write a function multi_search that takes a list and value as its argument. It should return a list of all positions in the list where the value occurs. If the value doesn't occur, this will be the empty list. For example,

>>> testlist = [5, 2, 9, 8, 9, 2, 6, 0, 9, 1]
>>> multi_search(testlist, 9)
[2, 4, 8]
>>> multi_search(testlist, 4)
[]
>>> multi_search(testlist, 0)
[7]
>>> multi_search(["a", "b", "a", "c"], "a")
[0, 2]

You may find it useful to start with the implementation of linear search from class. You can modify this to build (and then return) a list of the relevant positions.

Finding the Median

In lab10.py, write a function median that takes a list of numbers as its argument and returns the list's median.

The median is the value in the list that has an equal number of values that are larger and smaller. If the list has an even length, the median is the average of the two middle elements.

>>> median([32,10,54,23,21])
23
>>> median([42,13,80,85,22,43])
42.5

Hint: sort the list first. To test if a number is even, you can look at "n % 2 == 0".

Submitting

Submit all of your work through CourSys.

Updated Tue July 09 2024, 16:28 by ggbaker.