CS 1MD3 - Winter 2006 - Assignment #2

Generated for Student ID: 0570080

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 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 > 1-n: 
		x = aList[i]
		if x < theMin:
			theMin = x
			theArgMin = i
		i = i - 1
	return theArgMin

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

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 = 0
	while i < n:
		theNorm = theNorm + abs(aVector[i])**2
		i=i+1
	return pow(theNorm, O.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 isAnagram(str1, str2):
	"""Returns True if the two strings are anagrams of each other (i.e. if str2 is 
	simply a permutation of the letters of str1); otherwise returns False."""
	if len(str1) != len(str2):
		return False
	list1 = list(str1)
	list2 = list(str2)
	n = len(list1)
	for x in list1:		# For each character in list1...
		if x in list2:	# ...if that character appears in list2, remove it from list2.
			xPos = list2.index(x)
			list2 = list2[0:xPos] + list2[xPos+1:len(list2)]
		else:
			return False	
	if len(list2) == 0:	# If list2 is empty by this point, then the strings were anagrams
		return True
	else:
		return False