CS 1MD3 - Winter 2006 - Assignment #2
Generated for Student ID: 0561326
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 isPalindrome(aList):
"""Returns True if the list reads the same backwards and forwards."""
n = len(aList)
cursor = 0
while cursor < n:
if (aList[cursor] != aList[-cursor-1]):
return False
cursor=cursor+1
return True
2
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)
3
def deinterlaceEven(interlacedList):
"""Returns a list consisting of only the even elements of the given list.
For example, deinterlaceEven(['1', 'a', '2', 'b', '3', 'c']) returns [1,2,3]."""
n = len(interlacedList)
if n == 0:
return None
i = 0
evenList = []
while i < n:
evnList.append(interlacedList[i])
i = i+2
return evenList
4
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 = 1-n
while i <= 0:
theNorm = theNorm + abs(aVector[i])**2
i=i-1
return pow(theNorm, 0.5)
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 bubbleSort(aList):
"""Sorts the given list using the (in)famous BubbleSort algorithm."""
n = len(aList)
i = 0
while i < n-1:
j = 0
while j < n-i-1:
if aList[j+1] < aList[j]:
temp = aList[j]
aList[j] = aList[j+1]
aList[j+1] = temp
j = j+1
i = i+1