CS 1MD3 - Winter 2006 - Assignment #2
Generated for Student ID: 0568063
Due Date: Wednesday, February 8th
(You are responsible for verifying that your student number is correct!)
Part 1: Debugging
The following four functions are infested with bugs. Correct them by adding or changing a single
line in each one. Clearly indicate your changes with comments. If you add a line, append the
comment, "# added." If you change a line, append a comment to it containing the original, erroneous line.
Solutions submitted without comments will not be marked.
1
def reverseList(aList):
"""Reverses the elements of a list. Yes, yes... Python has a built-in function
to do that, but what if someone steals it? Ha! Bet you never thought of that,
did ya??"""
n = len(aList)
i = 0
while i < n/2:
j = -i-1
temp = aList[i]
aList[i] = aList[j]
aList[j] = temp
i = i+1
2
def argMax(aList):
"""Returns the index of the largest element in the list"""
n = len(aList)
if n <= 0:
return None
i = n-1
theArgMax = i
theMax = aList[theArgMax]
while i > 0:
x = aList[i]
if x > theMax:
theMax = x
theArgMax = i
i = i - 1
return theArgMax
3
def mean(numberList):
"""Returns the mean (i.e. average) value of the elements in the list"""
n = len(numberList)
if n == 0:
return None
theSum = 0
i = 0
while i < n:
x = NumberList[i]
theSum = theSum + x
i = i + 1
return float(theSum) / float(n)
4
def product(numberList):
"""Computes the product of all the list elements."""
n = len(numberList)
if n <= 0:
return None
theProduct = 1
i = 0
while i < n:
theProduct = theProduct * numberList[i]
i=i+1
return theProduct
Part 2: Testing
Create automated tests for the following function using PyUnit. Your tests should ensure that the code produces the expected result in all cases.
def isIsosceles(pt1, pt2, pt3):
"""Accepts three lists of floating point numbers, each list specifying a point in
(real) n-dimensional space. Returns True if the three points are the corners of an
isosceles triangle; returns False otherwise."""
n = len(pt1)
if len(pt2) != n or len(pt3) != n:
return False
edge1sqrd, edge2sqrd, edge3sqrd = 0, 0, 0
for x,y in zip(pt1,pt2):
edge1sqrd = edge1sqrd + (x-y)**2
for x,y in zip(pt1,pt3):
edge2sqrd = edge2sqrd + (x-y)**2
for x,y in zip(pt2,pt3):
edge3sqrd = edge3sqrd + (x-y)**2
if edge1sqrd==edge2sqrd==edge3sqrd: # We'll adopt the convention that equilateral ==> not isosceles
return False
if edge1sqrd==edge2sqrd or edge1sqrd==edge3sqrd or edge2sqrd==edge3sqrd:
return True
else:
return False