CS 1MD3 - Winter 2006 - Assignment #2

Generated for Student ID: 0470360

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 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

2
def deinterlaceOdd(interlacedList):
	"""Returns a list consisting of only the odd elements of the given list.
	For example, deinterlaceOdd(['1', 'a', '2', 'b', '3', 'c']) returns [a,b,c]."""
	n = len(interlacedList)
	if n <= 1:
		return None
	i = 1
	oddList = []
	while i < n:
		oddList.append(interlacedList[i])
	i = i+2	
	return oddList

3
def argMin(aList):
	"""Returns the index of the smallest element in the list"""
	n = len(aList) 
	if n <= 0:
		return None
	i = n-1
	theArgMin = i
	theMin = aList[theArgMin]
	while i >= 0: 
		x = aList[i]
		if x < theMin:
			theMin = x
			theArgMin = i
	return theArgMin

4
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.apend(interlacedList[i])	
		i = i+2
	return evenList


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