RecursionError · Exercises
Core Python

RecursionError Exercises

4 exercises that build on the Python RecursionError lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A RecursionError means a function kept calling itself (directly or indirectly) until Python's call-stack depth limit was hit, almost always because the recursion never reaches a base case. By the end you can read a RecursionError traceback, find the missing or unreachable base case, and choose between fixing the recursion, using a loop or an explicit stack. You will practise: Add the missing base case; Predict the outcome; Sum the digits recursively; Replace recursion with a stack.

0 / 4 completed

RecursionError practice exercises

1. Add the missing base case

Fix the bug Easy

countdown(n) should return a list like [3, 2, 1] for countdown(3) and an empty list for 0, but it recurses forever. Fix it without using a loop.

Your code
def countdown(n):
    return [n] + countdown(n - 1)

print(countdown(3))

2. Predict the outcome

Predict the output Easy

Read the code and type exactly what it prints, then press Check.

Read this code
import sys

def grow(n):
    return grow(n + 1)

def shrink(n):
    if n == 0:
        return "done"
    return shrink(n - 1)

sys.setrecursionlimit(150)
try:
    grow(1)
except RecursionError:
    print("grow failed")
print(shrink(10))
sys.setrecursionlimit(1000)

3. Sum the digits recursively

Write code Medium

Write a recursive function digit_sum(n) for a non-negative integer n that returns the sum of its digits, e.g. digit_sum(1234) is 10. Use n // 10 and n % 10, and give it a base case so it never raises RecursionError.

Your code
def digit_sum(n):
    pass

4. Replace recursion with a stack

Write code Hard

Write count_items(nested) that returns how many non-list items appear in a list that may contain lists inside lists, e.g. [1, [2, [3, 4]], 5] holds 5 items. It must handle nesting 3000 levels deep, so do not recurse: use a while loop with a list as an explicit stack.

Your code
def count_items(nested):
    pass

Next lessonPython AssertionError

More Python RecursionError examples · All Python exercises