Python Recursion
Table of Contents
Description
Recursion is a programming technique where a function calls itself to solve a smaller subproblem of the original problem. Each recursive call reduces the complexity of the task until it reaches a base condition, which stops the recursion. Recursion is often used in tasks like factorials, Fibonacci series, tree traversals, and divide-and-conquer algorithms.
Prerequisites
- Basic understanding of functions
- Understanding function calls and stack
- Familiarity with base and recursive cases
Examples
Here's a simple program in Python:
✅ Factorial of a Number (Classic Example) def factorial(n): # Base condition: factorial of 0 or 1 is 1 if n == 0 or n == 1: return 1 # Recursive call return n * factorial(n - 1) print(factorial(5)) # Output: 120 ✅ Fibonacci Sequence def fibonacci(n): # Base cases if n == 0: return 0 elif n == 1: return 1 # Recursive calls return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(6)) # Output: 8 ✅ Sum of Natural Numbers def sum_natural(n): # Base case if n == 0: return 0 # Recursive case return n + sum_natural(n - 1) print(sum_natural(5)) # Output: 15 ✅ Reverse a String def reverse_string(s): # Base case: if string is empty or one character if len(s) <= 1: return s # Recursive case: reverse the rest and append first character return reverse_string(s[1:]) + s[0] print(reverse_string("hello")) # Output: "olleh"Real-World Applications
File system traversal (like checking folders within folders)
Parsing nested structures (HTML/XML, JSON)
Helps sort or filter complex datasets on the fly
Tree and graph traversal in AI and compilers
Mathematical computations (factorials, permutations)
Backtracking problems (sudoku, mazes, N-Queens)
Where topic Can Be Applied
Data Structures: Trees, graphs, and stacks
Web Development: Rendering deeply nested data like JSON
AI/ML: Algorithms like decision trees, minimax (game AI)
Compilers: Parsing expressions (recursive descent parsing)
System Utilities: Recursively scanning folders/files
Resources
WatchTopic video source
A comprehensive video
VisitPython pdf
pdf on topic
Interview Questions
What is recursion in Python?
What are base and recursive cases?
How does Python manage recursion internally?
What is the default recursion limit in Python, and how can it be changed?
What are the advantages and disadvantages of recursion over loops?
Can you rewrite a recursive function using iteration?