CS 1MD3 - Winter 2006 - Assignment #2
Generated for Student ID: 0550969
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 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
2
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 = n
while i >= n/2:
j = n-i-1
temp = aList[i]
aList[i] = aList[j]
aList[j] = temp
i = i-1
3
def norm(aVector):
"""Computes the Euclidian norm of the given vector in R^n.
The Euclidean norm of x=(x1, x2, ..., xn) is defined as the square root of
x1^2 + x2^2 + ... + xn^2."""
n = len(aVector)
if n <= 0:
return None
theNorm = 0
i = 0
while i < n:
theNorn = theNorm + abs(aVector[i])**2
i=i+1
return pow(theNorm, 0.5)
4
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
return theArgMax
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 gcd(intList):
"""Finds the greatest common divisor among the list elements (in an inefficient way)."""
if len(intList) == 0:
return None
isDivisor = False
divider = 0
listMin = min(intList)
candidate = 1
while isDivisor == False:
divider = divider + 1
if listMin != divider * (listMin / divider): # if divider isn't a factor of listMin...
continue
candidate = listMin / divider
isDivisor = True
for x in intList:
if x != candidate * (x / candidate):
isDivisor = False
break
return candidate