Python Tutorial
Python Flow Control
Python Functions
Python Data Types
Python Date and Time
Python Files
Python String
Python List
Python Dictionary
Python Variable
Python Input/Output
Python Exceptions
Python Advanced
Recursion is a programming technique where a function calls itself directly or indirectly to solve a problem. It is often used as an alternative to loops for solving problems that can be broken down into smaller, similar subproblems. In this tutorial, we'll discuss the basics of recursion, how to create a recursive function, and some common use cases.
A recursive function typically consists of two parts:
Let's create a simple recursive function to calculate the factorial of a number.
def factorial(n): if n == 0: # Base case return 1 else: # Recursive case return n * factorial(n - 1) print(factorial(5)) # Output: 120
In this example, the base case is n == 0
, and the function returns 1
. The recursive case calls the factorial
function with the argument n - 1
. The recursion continues until the base case is reached.
Recursion is often used to solve problems that involve dividing the problem into smaller, similar subproblems. Some common examples include:
Here's an example of using recursion to solve the Fibonacci sequence:
def fibonacci(n): if n <= 1: # Base case return n else: # Recursive case return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(10)) # Output: 55
Recursion in Python has some limitations due to its maximum recursion depth, which defaults to 3000. This means that if a function calls itself more than 3000 times, a RecursionError
will occur. To overcome this limitation, you can use iterative solutions or apply techniques like memoization or dynamic programming.
In conclusion, recursion is a powerful programming technique that involves a function calling itself to solve problems that can be divided into smaller, similar subproblems. When creating a recursive function, ensure you have a base case to stop the recursion and prevent infinite loops. While recursion can be an elegant solution for certain problems, keep in mind its limitations and consider alternative approaches when necessary.
How to implement recursion in Python:
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)
Recursion vs. iteration in Python:
def factorial_iterative(n): result = 1 for i in range(1, n+1): result *= i return result
Recursive algorithms in Python:
def binary_search(arr, target, low, high): if low <= high: mid = (low + high) // 2 if arr[mid] == target: return mid elif arr[mid] < target: return binary_search(arr, target, mid + 1, high) else: return binary_search(arr, target, low, mid - 1) else: return -1
Handling base cases in recursive functions:
def power(x, n): if n == 0: return 1 else: return x * power(x, n-1)
Tail recursion in Python:
def factorial_tail_recursive(n, acc=1): if n == 0: return acc else: return factorial_tail_recursive(n-1, acc * n)
Common mistakes in recursive programming in Python:
def fibonacci(n): if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2)
Optimizing recursive functions in Python:
memo = {} def fibonacci_memoized(n): if n <= 1: return n elif n not in memo: memo[n] = fibonacci_memoized(n-1) + fibonacci_memoized(n-2) return memo[n]
Practical examples of recursion in Python:
class TreeNode: def __init__(self, value): self.value = value self.left = None self.right = None def inorder_traversal(node): if node: inorder_traversal(node.left) print(node.value) inorder_traversal(node.right)