Recursion in Python
Recursion in Python
Recursion involves a function calling itself directly or indirectly to solve a problem
by breaking it down into simpler and more manageable parts. In Python, recursion
is widely used for tasks that can be divided into identical subtasks.
In Python, a recursive function is defined like any other function, but it includes a
call to itself. The syntax and structure of a recursive function follow the typical
function definition in Python, with the addition of one or more conditions that lead
to the function calling itself.
Basic Example of Recursion:
def factorial(n):
if n == 0:
return
else:
return n * factorial(n-1)
print(factorial(5))
Output
120
Base Case: This is the condition under which the recursion stops. It is crucial to
prevent infinite loops and to ensure that each recursive call reduces the problem in
some manner. In the factorial example, the base case is n == 1.
Recursive Case: This is the part of the function that includes the call to itself. It
must eventually lead to the base case. In the factorial example, the recursive case
is return n * factorial(n-1).
Example:
def fibonacci(n):
# Base cases
if n == 0:
return 0
elif n == 1:
return 1
# Recursive case
else:
return fibonacci(n-1) + fibonacci(n-2)
# Example usage
print(fibonacci(10))
Output
55
Explanation:
Base Cases: If n == 0, the function returns 0. If n == 1, the function returns 1.
These two cases are necessary to stop the recursion.
Recursive Case: The function calls itself twice with the decrements of n (i.e.,
fibonacci(n-1) and fibonacci(n-2)), summing the results of these calls. This
division into smaller subproblems continues until the base cases are reached.
def nontail_fact(n):
# Base case
if n == 1:
return 1
# Non-tail recursive call because the multiplication happens after the call
else:
return n * nontail_fact(n-1)
# Example usage
print(tail_fact(5))
print(nontail_fact(5))
Output
120
120
Recursion vs Iteration
Recursion:
Recursion is often more intuitive and easier to implement when the problem is
naturally recursive, like tree traversals.
It can lead to solutions that are easier to understand compared to iterative ones.
Iteration:
Iteration involves loops (for, while) to repeat the execution of a block of code.
It is generally more memory-efficient as it does not involve multiple stack
frames like recursion.