15a Recursion
15a Recursion
CS100/CS101 – Python
Multiplication – Iteration
●
Caculate a * b
● aa ++ aa ++ aa ++ ...
... ++ aa
Multiplication – Recursion
●
Caculate a * b
● aa ** bb == aa ++ aa ++ aa ++ ...
... ++ aa
== aa ++ aa ++ aa ++ ...
... ++ aa
== aa ++ a*(b-1)
a*(b-1)
Multiplication – Recursion
●
recursive step
– think how to reduce problem to a simpler/smaller
version of same problem
●
Multiplication – Recursion
●
recursive step
– think how to reduce problem to a simpler/smaller
version of same problem
●
base case
– keep reducing problem until reach a simple case that
can be solved directly
– when b = 1, a*b = a
Factorial
n!
n! == n*(n-1)*(n-2)*(n-3)*
n*(n-1)*(n-2)*(n-3)* ...
... ** 11
Factorial
n!
n! == n*(n-1)*(n-2)*(n-3)*
n*(n-1)*(n-2)*(n-3)* ...
... ** 11
Factorial
n!
n! == n*(n-1)*(n-2)*(n-3)*
n*(n-1)*(n-2)*(n-3)* ...
... ** 11
●
for what n do we know the factorial?
– n=1 if
if nn ==
== 1:
1:
return
return 11
Factorial
n!
n! == n*(n-1)*(n-2)*(n-3)*
n*(n-1)*(n-2)*(n-3)* ...
... ** 11
●
for what n do we know the factorial?
if
if nn ==
== 1:
– n=1 return
1:
return 11
●
Reduce - Rewrite in terms of something simpler
to reach base case
else:
else:
– n*(n-1)! return
return n*factorial(n-1)
n*factorial(n-1)
Recursion Examples
●
Generate Sequences
– Fibonacci sequence
●
Eg. Match parentheses, Binary search, GCD,
Towers of Hanoi, etc.
Recursion
●
Algorithmically: a way to design solutions to
problems by divide-and-conquer or decrease-
and-conquer
– reduce a problem to simpler versions of the same
problem
Recursion
●
Semantically: a programming technique where
a function calls itself
– in programming, goal is to NOT have infinite
recursion
– must have 1 or more base cases that are easy to
solve
– must solve the same problem on some other input
with the goal of simplifying the larger problem input