CS 1MD3 - Winter 2006 - Assignment #2
Generated for Student ID: 0571661
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 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:
evenList.append(interlacedList[i])
i = i+2
return evenList
2
def hammingDistance(str1, str2):
"""Returns the Hamming distance (or "edit distance") between two strings of the
same length. Hamming distance is defined as the minimum number of characters which
must be changed to make the strings identical. For example, the Hamming distance
between "Python" and "Athlon" is 4 (only the last two letters are the same);
the Hamming distance between "noodle" and "needle" is 2 (only the second and
third letters differ)."""
if len(str1) != len(str2):
return None
list1 = list(str1)
list2 = list(str2)
n=len(list1)
distance = 0
i = 1-n
while i <= 0:
if list1[i] != list2[i]:
distance = distance + 1
i=i-1
return distance
3
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]):
return False
cursor=cursor+1
return True
4
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
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