Docsity

Recursion: concepts, examples, and makeChange, Lecture notes of Web Programming and Technologies

Partial preview of the text

Download Recursion: concepts, examples, and makeChange and more Lecture notes Web Programming and Technologies in PDF only on Docsity!

Recursion: concepts,

examples, and makeChange

Acknowledgement: The following slides are

adopted, some with minor revisions, from

several lecture slides of the CS5 Green

course at Harvey Mudd.

Factorial: Iteration Code

n! = n(n-1)(n-2)… 1 def factorial(n): result = 1 for k in range(1, n+1): result = result * k return result

Recursion…

n! = n(n-1)(n-2)… 1 n! = n x (n-1)! “inductive definition” 0! = 1 “base case” Why is 0! = 1?

Math Induction = CS Recursion

n! = n  (n-1)! Math inductive definition Python (Functional) recursive function

recursive factorial

def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)

Is Recursion Magic?

recursive factorial

def factorial(n): if n == 0: return 1 else: return nfactorial(n-1)* factorial(3): return 3 * factorial(2) return 2 * factorial(1)

Is Recursion Magic?

recursive factorial

def factorial(n): if n == 0: return 1 else: return nfactorial(n-1)* factorial(3): return 3 * factorial(2) return 2 * factorial(1) return 1 * factorial(0)

Is Recursion Magic?

recursive factorial

def factorial(n): if n == 0: return 1 else: return n*factorial(n-1) factorial(3): return 3 * factorial(2) return 2 * factorial(1) return 1 * factorial(0)

Is Recursion Magic?

recursive factorial

def factorial(n): if n == 0: return 1 else: return n*factorial(n-1) factorial(3): return 3 * factorial(2) return 2 * factorial(1) return 1 * factorial(0)

Computing the length of a list

>>> len([1, 42, “spam”])

>>> len([1, [2, [3, 4]]])

def len(L):

‘’’returns the length of list L’’ ’

Python has this built-in!

Computing the length of a list

>>> len([1, 42, “spam”])

>>> len([1, [2, [3, 4]]])

def len(L):

‘’’returns the length of list L’’ ’

if L == []: return 0 # base case

Python has this built- in!

Summing up the numbers in a list >>> sum([3, 42, 7]) 52 >>> sum([42]) 42 >>> sum([]) 0 def sum(L): ‘’’returns the sum of numbers in the list’’’ Python has this built-in too! Worksheet

Summing up the numbers in a list >>> sum([1, 42, 7]) 50 >>> sum([42]) 42 >>> sum([]) 0 def sum(L): ‘’’returns the sum of numbers in the list’’’ if L == []: return 0 The base case takes care of the simplest case we could get.

Summing up the numbers in a list >>> sum([1, 42, 7]) 50 >>> sum([42]) 42 >>> sum([]) 0 def sum(L): ‘’’returns the sum of numbers in the list’’’ if L == []: return 0 else: return L[0] + sum(L[1:])

Recursion = :^)

“To understand recursion, you must first understand recursion”

  • anonymous Mudd alum