W9PPS2
W9PPS2
Recursion
Introduction to Recursion
Recursion is a programming technique where a function calls itself to solve a problem. A recursive function
must have a base condition to avoid infinite loops.
def factorial(n):
if n == 0 or n == 1:
return 1 # Base condition
return n * factorial(n - 1) # Recursive call
Each function call is added to the call stack and executed in reverse order upon reaching the base condition.
print(fibonacci(6)) # Output: 5
Recursive Approach:
Iterative Approach:
Additional Examples
Conclusion
Recursion is useful for problems like factorial, Fibonacci, and tree traversals.
Divide and Conquer optimizes sorting and searching operations.
Iteration is often more space-efficient compared to recursion.
Practice:
1. Factorial of a Number
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
def fibonacci(n):
if n <= 0:
return "Invalid input"
if n == 1:
return 0
if n == 2:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(6)) # Output: 5
Write a recursive function to find the sum of the first N natural numbers.
def sum_n(n):
if n == 0:
return 0
return n + sum_n(n - 1)
print(sum_n(5)) # Output: 15 (1+2+3+4+5)
4. Reverse a String
def reverse_string(s):
if len(s) == 0:
return s
return s[-1] + reverse_string(s[:-1])
print(reverse_string("hello")) # Output: "olleh"
Write a recursive function to find the GCD of two numbers using the Euclidean algorithm.
9. Tower of Hanoi
def sum_of_digits(n):
if n == 0:
return 0
return n % 10 + sum_of_digits(n // 10)
print(sum_of_digits(1234)) # Output: 10 (1+2+3+4)