0% found this document useful (0 votes)
14 views

Untitled Document (34)

Uploaded by

kylemessi001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Untitled Document (34)

Uploaded by

kylemessi001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Advanced Lecture on Recursion

1. What Is Recursion?

Recursion is a method of solving problems where a function calls itself as


a subroutine. This approach breaks a problem into smaller, more
manageable subproblems until a base condition is met.

2. Anatomy of a Recursive Function

Every recursive function must have two essential components:

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.

Example: Calculating Exponents

The following recursive function calculates the result of base^exponent.

Code:

def get_power(base, exponent):


if exponent == 1: # Base case

return base

else: # Recursive step

return base * get_power(base, exponent - 1)

# Example usage

print(get_power(2, 4)) # Output: 16

Explanation:

1. For base = 2 and exponent = 4:


○ The first call computes 2 * get_power(2, 3).
○ The next call computes 2 * get_power(2, 2).
○ This process continues until the base case (exponent == 1)
is met.
2. Once the base case is reached, the calls “unwind,” returning the
results back up the stack.

3. How Recursion Works Internally

When a recursive function is called, Python:

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

4. Recursion vs. Iteration

Feature Recursion Iteration

Concept Function calls itself Uses loops (e.g., for,


while)

Space Higher due to call stack Lower, as no additional


Complexity stack is used
Code More elegant for certain Simpler for repetitive tasks
Elegance problems

Efficiency Can be inefficient for large More efficient for most use
problems cases

Example: Fibonacci Sequence

Recursive Version:

def fibonacci(n):

if n == 0 or n == 1: # Base cases

return n

else: # Recursive step

return fibonacci(n - 1) + fibonacci(n - 2)

Iterative Version:

def fibonacci_loop(n):

n1, n2 = 0, 1

for _ in range(n):
n1, n2 = n2, n1 + n2

return n1

Comparison:

● Recursive Version: Elegant but inefficient for large n due to


repeated calculations.
● Iterative Version: More efficient and uses less memory.

5. Advantages of Recursion

1. Simplifies Complex Problems: Ideal for tasks that can naturally be


divided into smaller subproblems (e.g., factorials, traversing trees).
2. Readable Code: Some problems, like traversing hierarchical
structures, are more intuitive with recursion.
3. Powerful for Mathematical Computations: Solving equations,
generating sequences, or handling fractals.

6. Challenges of Recursion

1. Stack Overflow: If the recursion depth exceeds Python’s default limit


(typically 1000), it results in a RecursionError.
Solution: Use an iterative approach or optimize the recursion (e.g.,
tail recursion).
2. Performance Issues: Recursive functions may recompute results
multiple times.
Solution: Use memoization to cache intermediate results.

7. Real-World Applications of Recursion


1. Tree Traversals
○ Recursion is a natural fit for traversing hierarchical data
structures like file systems or XML/HTML documents.
2. Divide and Conquer Algorithms
○ Merge Sort, Quick Sort, and Binary Search rely on recursion.
3. Dynamic Programming
○ Problems like the Knapsack Problem and Longest Common
Subsequence use recursion with memoization.

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?

You might also like