Skip to content

Module 18 · Algorithms and Problem Solving — topic 13 of 18

Recursion problems

Solving problems recursively: base cases and recursive cases, classic problems (factorial, digit sums, reversing strings, fast power, flattening nested lists, permutations, Tower of Hanoi), and recognising when recursion fits.

Beginner 12 min read·Lesson 273 of 306 in Python Programming

Learning objectives

  • Design base and recursive cases
  • Solve classic recursive problems
  • Recognise problems with naturally recursive structure

Definition

A recursive solution solves a problem by solving smaller instances of the same problem. It needs a base case that is answered directly and a recursive case that reduces the problem towards the base case.

Introduction

Some problems are defined in terms of themselves: a folder contains files and folders, a permutation is a choice followed by a permutation of the rest. Recursion matches that structure directly.

Why it matters

Trees, nested data, backtracking searches and divide-and-conquer algorithms are much clearer recursively than with loops.

Detailed explanation

Every recursive function needs at least one base case that returns without recursing — otherwise it recurses until RecursionError.

The recursive case must make the problem smaller: a shorter list, a smaller number, a sublist.

Trust the recursion: assume the recursive call returns the right answer for the smaller problem and focus on combining it.

Divide and conquer splits a problem into parts, solves each recursively and combines the results (fast power, merge sort).

Recursion fits nested structures naturally: nested lists, folder trees, JSON documents.

Backtracking problems (permutations, puzzles) explore choices recursively.

Python limits recursion depth (about 1,000 by default) and doesn't optimise tail calls, so very deep recursion should be rewritten as a loop.

Repeated subproblems (like naive Fibonacci) make recursion exponentially slow; memoisation fixes this.

Syntax

Python
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1) # smaller problem
  • Always have a base case.
  • Make the problem smaller.
  • Trust the recursive call.

Code examples

Factorial and digit sums

Python
def factorial(n):
return 1 if n <= 1 else n * factorial(n - 1)
def digit_sum(n):
return n if n < 10 else n % 10 + digit_sum(n // 10)
print(factorial(6), digit_sum(98765))
Output
720 35

Reversing and fast power

Python
def reverse(s):
return s if len(s) <= 1 else reverse(s[1:]) + s[0]
def power(base, exp):
if exp == 0:
return 1
half = power(base, exp // 2)
return half * half * (base if exp % 2 else 1)
print(reverse("recursion"), power(2, 10), power(3, 5))
Output
noisrucer 1024 243

More examples

Nested lists, permutations and Hanoi

Python
def flatten(items):
out = []
for x in items:
if isinstance(x, list):
out.extend(flatten(x))
else:
out.append(x)
return out
def permutations(s):
if len(s) <= 1:
return [s]
return [ch + rest for i, ch in enumerate(s) for rest in permutations(s[:i] + s[i + 1:])]
def hanoi(n, src="A", dst="C", via="B", moves=None):
if moves is None:
moves = []
if n > 0:
hanoi(n - 1, src, via, dst, moves)
moves.append(f"{src}->{dst}")
hanoi(n - 1, via, dst, src, moves)
return moves
print(flatten([1, [2, [3, 4]], [], [[5]]]))
print(permutations("abc"))
moves = hanoi(3)
print(len(moves), moves[:3])
Output
[1, 2, 3, 4, 5]
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
7 ['A->C', 'A->B', 'C->B']

Step-by-step explanation

  • flatten recurses only into elements that are lists, however deeply nested.
  • Each permutation is a first character followed by a permutation of the remaining characters.
  • Hanoi moves n − 1 discs out of the way, moves the largest, then moves the n − 1 discs back on top: 2ⁿ − 1 moves in total.

Expected output

Running “Nested lists, permutations and Hanoi” prints exactly:

TextOutput
[1, 2, 3, 4, 5]
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
7 ['A->C', 'A->B', 'C->B']

Practical applications

  • Walking folder trees and parsing nested JSON.
  • Solving puzzles such as Sudoku with backtracking.

Best practices

  • Write the base case first.
  • Use recursion for naturally recursive structures.
  • Switch to loops or memoisation when depth or repetition grows.

Common mistakes

No reachable base case

Avoid

def countdown(n):
print(n)
countdown(n - 1)

Prefer

def countdown(n):
if n < 0:
return
print(n)
countdown(n - 1)

Without a base case the function recurses until RecursionError.

Important notes

  • sys.getrecursionlimit() shows the current depth limit.

Key takeaways

  • Recursion needs a base case and a smaller subproblem.
  • It suits nested data, divide and conquer and backtracking.
  • Watch depth limits and repeated work.

Try it yourself

  1. 1
    Write a recursive function that counts the files in a nested dictionary representing folders.
  2. 2
    Generate all subsets of a list recursively.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
Practise this topic