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