IntermediateChallenge 24 of 34

Write memoize

Write a memoize that results by positional , and exposes the number of cache hits as func.hits. Then use it on the slow recursive count_paths(rows, cols) so that count_paths(16, 16) returns instantly.

Exercise

Write memoize

4 checks
import functools


def memoize(func):
    ...


@memoize
def count_paths(rows, cols):
    """Number of lattice paths from the top-left to bottom-right corner moving only right or down."""
    if rows == 1 or cols == 1:
        return 1
    return count_paths(rows - 1, cols) + count_paths(rows, cols - 1)


print(count_paths(16, 16), count_paths.hits)
 
Python (loads on first run)Ctrl+Enter runs
Output
Press Run to try your code, then Check answer to grade it.