CS 1MD3 - Winter 2006 - Assignment #2

Generated for Student ID: 0369864

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 = 0
	theArgMax = i
	theMax = aList[theArgMax]
	whi1e i < n:	
		x = aList[i]
		if x > theMax:
			theMax = x
			theArgMax = i
		i = i + 1
	return theArgMax

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

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 = n-1
	while i > 0: 
		theNorm = theNorm + abs(aVector[i])**2
		i=i-1
	return pow(theNorm, 0.5)

4
def isPalindrome(aList):
	"""Returns True if the list reads the same backwards and forwards."""
	n = len(aList)
	cursor = n-1
	while cursor >= 0:
		if (aList[cursor] != aList[-cursor-1]):
			return False
		cursor=cursor+1	
	return True 


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 indexOf(strg, sub):
	"""Returns the index of the first occurrence of the substring 'sub' within the string 'strg,' 
	or -1 if 'sub' isn't a substring of 'strg.'"""
	if len(sub) > len(strg):
		return -1
	index = 0
	foundIt = False
	while (index <= len(strg)-len(sub)) and (foundIt==False):
		i = 0
		while (i < len(sub)) and (strg[index+i] == sub[i]):
			i = i+1
		if i == len(sub):
			foundIt = True
		else:
			index = index + 1
	if foundIt == True:
		return index
	else:
		return -1