CMPT 120 Lab 9

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

  1. Create a function triangle, which takes a string as its argument and prints the successive characters of the string on each line. For example,
    >>> triangle("CMPT")
    C
    CM
    CMP
    CMPT
    1. Do this using string slices.
    2. You can do this without using string slices: come up with another way to implement the same function without slices.
  2. For this question, you will create two similar functions that actually work very differently. Both of these functions will be used to remove the last item from a list, but will operate in different ways.
    1. Write a function chop1 that returns its argument with the last item removed. It should not change the argument, but should return a copy without the last item.
      >>> testlist = [0,1,2,3,4]
      >>> chop1(testlist) # note: returns modified copy
      [0, 1, 2, 3]
      >>> print testlist # note: original unchanged
      [0, 1, 2, 3, 4]
    2. Write a function chop2 that removes the last item from a list given as its argument. The existing list should be changed in-place; the function should not return anything.
      >>> testlist = [0,1,2,3,4]
      >>> chop2(testlist) # note: no return value
      >>> print testlist
      [0, 1, 2, 3]

    The difference between these two functions is important. The first operates like all of the other functions we've written: taken arguments and returned whatever results it created. The second is possible because lists are mutable: the function takes the reference to the list and changes it in-place.

  3. 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 listed in removelist. So, in the example, we want to remove elements 2, 5, and 7 from targetlist. After this it will be [0, 10, 30, 40, 60, 80, 90].

    Your first thought about how to do this might not work. You can download a broken item remover.

    1. Describe why the program linked above doesn't work: it loops over the items in removelist and deletes each one. Why doesn't that remove the correct items?
    2. Fix the code so it removes the correct items.