Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 05 / Topic 7 of 9

Recursion

A recursive function calls itself on a smaller problem. Think of Russian dolls: open one, find a smaller one inside, until the smallest doll that does not open. That smallest case is the base case. It stops the calls. Every recursive function needs one.

Real-world example: factorial and the sum of digits of a number.

def factorial(n: int) -> int:
    if n <= 1:                   # base case
        return 1
    return n * factorial(n - 1)  # smaller problem

print(factorial(5))              # 120

def sum_of_digits(n: int) -> int:
    if n < 10:                   # base case: one digit
        return n
    return n % 10 + sum_of_digits(n // 10)

print(sum_of_digits(4096))       # 19

Folder size idea

A folder holds files and other folders. To find its size, add the files, then ask each sub-folder for its size (same question, smaller problem). That is recursion. In the example a folder is a nested dict, and isinstance(value, dict) (True if value is a dict) tells a sub-folder from a file. See examples/05_recursion_folder_size.py.

Recursion limit

Python stops very deep recursion (about 1000 calls by default) with RecursionError. Deep recursion is also slow and uses a lot of memory. For very deep cases, use a for or while loop instead.

import sys                       # import is taught in Part 7
print(sys.getrecursionlimit())   # 1000

๐Ÿ” Going deeper: every call waits in memory (on the call stack) until its inner call returns. Python does not optimise "tail calls", so depth really costs memory and time. You can raise the limit with sys.setrecursionlimit(), but that is rarely the right fix: it only hides the problem. Turn deep recursion into a loop instead.

Done here? The practice set for Part 5 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide