Untitled Document (34)
Untitled Document (34)
1. What Is Recursion?
1. Base Case
○ The stopping condition that prevents infinite recursion.
○ Without a base case, the function would keep calling itself
indefinitely, causing a stack overflow error.
2. Recursive Step
○ The part where the function calls itself to solve smaller
instances of the problem.
○ Typically, the parameters are adjusted to move closer to the
base case.
Code:
return base
# Example usage
Explanation:
1. Allocates memory for the function call, including variables and the
current state.
2. Pauses the current call and moves to the next recursive call.
3. Once the base case is reached, the calls “unwind” in reverse order,
returning results.
Call Stack Visualization for get_power(2, 4):
Call Result
get_power 2
(2, 1)
get_power 2 * 2
(2, 2) = 4
get_power 2 * 4
(2, 3) = 8
get_power 2 * 8
(2, 4) = 16
Efficiency Can be inefficient for large More efficient for most use
problems cases
Recursive Version:
def fibonacci(n):
if n == 0 or n == 1: # Base cases
return n
Iterative Version:
def fibonacci_loop(n):
n1, n2 = 0, 1
for _ in range(n):
n1, n2 = n2, n1 + n2
return n1
Comparison:
5. Advantages of Recursion
6. Challenges of Recursion
Thinking Points
1. Why does recursion require a base case, and what happens if it’s
missing?
2. Can every recursive problem be converted to an iterative solution?
Why might recursion still be preferred in some cases?
3. How can memoization improve recursive function performance?