Python practice

Python recursion practice questions

8 problems, ordered from easiest. They run in your browser, and 1 is free.

Start with Flatten Nested Lists

The idea in a minute

A recursive function solves a problem by calling itself on a smaller version of the same problem. Every recursive function needs a base case, which is the smallest problem it can answer directly.

The problems start with factorial and sums and move on to nested lists, where recursion is the natural tool.

Example: Sum a nested list

def total(items):
    result = 0
    for item in items:
        if isinstance(item, list):
            result += total(item)
        else:
            result += item
    return result

print(total([1, [2, 3], [4, [5]]]))

What it prints

15

What to watch for

  • Write the base case first. Without it the function never stops.
  • Each call must make the problem smaller, or it will run forever.
  • Python stops very deep recursion with a RecursionError.

Recursion problems

  1. Flatten Nested Listsbeginner · Free
  2. Flatten nested JSON to dotted keysintermediate · Locked
  3. Unflatten dotted keysintermediate · Locked
  4. Extract all email addresses from a nested payloadintermediate · Locked
  5. Retry a flaky operation with a capintermediate · Locked
  6. Memoize an expensive lookup functionintermediate · Locked
  7. Flatten a directory listing into pathsintermediate · Locked
  8. Detect a cycle in a task dependency mapadvanced · Locked

Want a guided order across every topic? Open the practice sheets or the Python hub.