

































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


































































n! = n(n-1)(n-2)… 1 def factorial(n): result = 1 for k in range(1, n+1): result = result * k return result
n! = n(n-1)(n-2)… 1 n! = n x (n-1)! “inductive definition” 0! = 1 “base case” Why is 0! = 1?
n! = n (n-1)! Math inductive definition Python (Functional) recursive function
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)
def factorial(n): if n == 0: return 1 else: return nfactorial(n-1)* factorial(3): return 3 * factorial(2) return 2 * factorial(1)
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)
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)
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)
Python has this built-in!
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:])
“To understand recursion, you must first understand recursion”