This site applies only to CMPT 120 D1 (Burnaby) in Summer 2011. See the other instructors' pages for other sections.
-
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- Do this using string slices.
- You can do this without using string slices: come up with another way to implement the same function without slices.
-
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.
-
Write a function
chop1that 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] -
Write a function
chop2that 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.
-
Write a function
-
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
targetlistand delete the elements listed inremovelist. So, in the example, we want to remove elements 2, 5, and 7 fromtargetlist. 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.
-
Describe why the program linked above doesn't work: it loops over the items in
removelistand deletes each one. Why doesn't that remove the correct items? - Fix the code so it removes the correct items.
-
Describe why the program linked above doesn't work: it loops over the items in