
Python practice
Python recursion practice questions
8 problems, ordered from easiest. They run in your browser, and 1 is free.
Start with Flatten Nested ListsThe 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
15What 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
- Flatten Nested Listsbeginner · Free
- Flatten nested JSON to dotted keysintermediate · Locked
- Unflatten dotted keysintermediate · Locked
- Extract all email addresses from a nested payloadintermediate · Locked
- Retry a flaky operation with a capintermediate · Locked
- Memoize an expensive lookup functionintermediate · Locked
- Flatten a directory listing into pathsintermediate · Locked
- Detect a cycle in a task dependency mapadvanced · Locked
Want a guided order across every topic? Open the practice sheets or the Python hub.