PythiloMedium · 20 min · Task 16 of 20 · progress kept in this browser

Tiling with memoization

Tiles come in lengths 1, 2 and 3. How many different ordered ways can you cover a strip of length n?

The first tile placed leaves a smaller strip, so the answer is a sum of three smaller answers:

def ways(n):
    if n < 0:
        return 0
    if n == 0:
        return 1
    return (ways(n - 1) + ways(n - 2)
            + ways(n - 3))

That is correct but hopeless for large n. It solves the same strips over and over, and the calls grow exponentially.

Your task

Write tile_ways(n) returning the number of ordered ways to cover a strip of length n with tiles of lengths 1, 2 and 3, using recursion with memoization. It must return quickly for n = 60.