Python Recursion
Recursion is a programming technique where a function calls itself to solve smaller instances of a problem. A recursive function must have a base case to prevent infinite recursion and a recursive case where the function calls itself.
Components of Recursion:
- Base Case: The condition under which the recursion stops.
- Recursive Case: The logic in which the function calls itself with a reduced or simpler problem.
Example
def factorial(n): if n == 0: # Base case return 1 else: # Recursive case return n * factorial(n - 1) # Test the function print(factorial(5)) # 120
Points to create recursive functions
- Clearly define the base case.
- Ensure the recursive step progresses toward the base case.
- Use recursion for problems that naturally fit recursive solutions.
- Consider iterative alternatives for performance-critical tasks.