Python Recursion
Python Recursion
Recursive Functions
Alternatively:
Consider
5! =
5x4x3x2x1
can be re-
written as 5!
=5x4!
factorial(n) = n * factorial(n-1)
In general
n! = nx(n-1)!
Recursive Functions
Alternatively:
Consider
factorial(n) = n * factorial(n-1)
Recursive Functions
Recursive Functions
Known
Base case
Recursive Functions
Base case
Recursive step
Recursive Functions
• No computation in first
phase, only function calls
• Deferred/Postponed fact (4)
4 * fact (3)
computation 4 * (3 * fact (2))
4 * (3 * (2 * fact (1)))
– after function calls 4 * (3 * (2 * (1 * fact (0))))
terminate, computation 4 * (3 * (2 * (1 * 1)))
4 * (3 * (2 * 1))
starts 4 * (3 * 2)
• Sequence of calls have 4*6
24
to be remembered Execution trace for n = 4
Courtesy Prof PR Panda CSE Department IIT Dehi
Another Example (Iterative)
Iterative
Source:https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-
programming-in-python-fall-2016/lecture-slides-code/
Another Example (Recursive)
Iterative Algorithm
Recursive
Source:https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-
programming-in-python-fall-2016/lecture-slides-code/
Recursive Functions
• Size of the problem reduces at each step
• The nature of the problem remains the same
• There must be at least one terminating condition
b if a mod b = 0
gcd (a, b) =
gcd (b, a mod b) otherwise
Iterative Recursive
Algorithm Algorithm
GCD Algorithm
b if a mod b = 0
gcd (a, b) =
gcd (b, a mod b) otherwise
0 n=1
fib (n) = 1 n=2
fib (n-1) + fib (n-2) n > 2
Recursive
Algorithm
fib (6)
fib (3) fib (2) fib (2) fib (1) fib (2) fib (1)
1 if n = 0
power(x,n) =
x * power(x,n-1) otherwise
Power Function
• Efficient power function
• Fast Power
– fpower(x,n) = 1 for n = 0
– fpower(x,n) = x * (fpower(x, n/2))2 if n is odd
– fpower(x,n) = (fpower(x, n/2))2 if n is even
Power Function
• Efficient power function
Towers of Hanoi Problem
• 64 gold discs with different
diameters
• Three poles: (Origin, Spare, Final)
• Transfer all discs to final pole
from origin
– one at a time
– spare can be used to temporarily
store discs Origin Spare Final
– no disk should be placed on a
smaller disk
• Intial Arrangement:
– all on origin pole, largest at bottom,
next above it, etc.
Courtesy Prof PR Panda CSE Department IIT Dehi
3-Step Strategy
Open( )
Syntax
file_object = (“filename.txt”, “Access Mode”)
File pointer