Start free

A level · 8 exercises

Python recursion

A recursive function calls itself on a smaller version of the problem, until it reaches a case small enough to answer directly (the base case).

Trust the smaller call to be right, and only work out how to build this answer from it.

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

print(factorial(5))

Watch for: Without a base case, or if the problem doesn't get smaller, it never stops: Python gives up with a RecursionError.

Exercises

  1. Towers of HanoiMove n disks from peg A to peg C using peg B, one disk at a time, never putting aAdvanced
  2. All binary stringsPrint every string of 0s and 1s of length n, in increasing order, using recursion.Advanced
  3. PermutationsPrint every different ordering of the letters of a word, in alphabetical order,Advanced
  4. Subsets with a sumCount the subsets (choices of positions) of the list whose numbers add up to theAdvanced
  5. Flatten a nested listA list can contain numbers and other lists, nested to any depth.Advanced
  6. Paths in a gridIn a grid of r rows and c columns you start top-left and may only move right orAdvanced
  7. Climbing stairsYou climb a staircase taking 1, 2 or 3 steps at a time.Advanced
  8. Fair splitCan the numbers be split into two groups with the same sum?Advanced
Start with “Towers of Hanoi”