Fall 2006 Midterm 2 Review: List functions
a)
def addItems(list):
a=0
for i in list:
a=i+a
print a
Jeffrey Wells
| Everything looks right except the last line. You're required to use 'return' rather than 'print'. - Bobby Mathew |
(b)
def rmMid(list):
length = len(list)
middle = length/2.0
if middle <> int(middle):
list = list[:int(middle)] + list[int(middle)+1:]
else:
list = list[:int(middle)-1] + list[int(middle):]
return list
David Poore
def rmMid(list):
length=list.len()
loc=int(length/2.0+.5)-1
list=list[ :loc]+list[loc+1:]
return list
Stacy Schwaiger
| You need to change the second line to length = len(list). After that, the function will work. - Bobby Mathew |
Why?
| Because list.len() will give a syntax error. It has to be len(list). - Bobby Mathew |
Please clarify why it is necessary to use 'int' in the example posted by Stacy?
Please clarify why it is necessary to use 'int' in the example posted by Stacy?
| int() is used to make something an integer. This is needed because you cannot access a non-integer sample (in this case it could be a float), so if you tell the function that you want to make it an integer regardless, you avoid this problem just in case. -Brittany Duncan |
def rmMid(list):
middle = len(list)/2
list.remove(list[middle])
return list
How does this work for an odd list? If the list was say 9 numbers, dividing that by 2 would make it 4... not 5, so how could I remove the 5?
| That's right. You need to do something different for odd and even-length lists. There is a way to do this that makes use of the fact that integer division throws away the fractional part. Try this: invent and use a function like "if oddLength(list):...". as if that function already existed. Get your main function to work, and only then see if you can work out how to write oddLength. If you can't work it out, don't worry. You solved 75% of the problem. Colin Potts |
Link to this Page