Previous Lecture Lecture 17 Next Lecture

Lecture 17, Tue 03/05

Recursion

Recorded Lecture: 3_5_24

Recursion

Properties of Recursion

Example: Computing sum of first n numbers

def summation(n):
	''' Returns the sum of the first n numbers (assuming
		n >= 0) '''

	# Approach 1: While loops
	#temp = 0
	#result = 0
	#while temp <= n:
	#	result += temp
	#	temp += 1
	#return result

	# Approach 2: For loops
	#result = 0
	#for x in range(n+1):
	#	result += x
	#return result

	# Approach 3: Recursion
	if n == 0: # could also think of using n == 1
		return 0
	return n + summation(n-1)

print(summation(0))
print(summation(1))
print(summation(3))
print(summation(5))

Recursive Search and Binary Search

def find(collection, item):
	for element in collection:
		if element == item:
			return True
	return False

assert find([1, 5, 3, 7, 4, 2], 1) == True
assert find([1, 5, 3, 7, 4, 2], 2) == True
assert find([1, 5, 3, 7, 4, 2], 7) == True
assert find([1, 5, 3, 7, 4, 2], 8) == False
def find(collection, item):
	if len(collection) == 0:
		return False

	if collection[0] == item:
		return True
	return find(collection[1:], item)
def binarySearch(intList, item):
	if len(intList) == 0: # base case
		return False

	mid = len(intList) // 2

	if intList[mid] == item:
		return True
	elif item < intList[mid]:
		return binarySearch(intList[0:mid], item)
	else:
		return binarySearch(intList[mid+1:], item)

assert binarySearch([1,2,3,4,5,6,7,8,9,10], 5) == True
assert binarySearch([1,2,3,4,5,6,7,8,9,10], -1) == False
assert binarySearch([1,2,3,4,5,6,7,8,9,10], 11) == False
assert binarySearch([1,2,3,4,5,6,7,8,9,10], 1) == True
assert binarySearch([1,2,3,4,5,6,7,8,9,10], 10) == True

Accumulator Pattern with Recursion

def countMultiples(collection, num):
	if len(collection) == 0:
		return 0
	if collection[0] % num == 0:
		return 1 + countMultiples(collection[1:], num)
	return countMultiples(collection[1:], num)

assert countMultiples([1,2,3,4,5,6,7], 3) == 2
assert countMultiples([1,2,3,4,5,6,7], 2) == 3
assert countMultiples([1,2,3,4,5,6,7], 8) == 0
def keepMultiples(collection, num):
	if len(collection) == 0:
		return []
	if collection[0] % num == 0:
		return [collection[0]] + keepMultiples(collection[1:], num)
	return keepMultiples(collection[1:], num)

assert keepMultiples([1,2,3,4,5,6,7], 3) == [3, 6]
assert keepMultiples([1,2,3,4,5,6,7], 2) == [2, 4, 6]