Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Cache the Last Result with a Closure

Build a closure that remembers the last call and its result to avoid re-computation when called again with the same arguments.

Python practice15 minClosures & Function FactoriesIntermediateLast updated April 13, 2026

Problem statement

Sometimes you want a lightweight memoization that only remembers the last call — useful for streaming or sequential computations where the same inputs might be repeated consecutively. Implement cache_last(func) which returns a wrapped function. The wrapper should: - Call func(*args, **kwargs) the first time for a given set of arguments. - Store (cache) a deep copy of the arguments and the result. - On subsequent calls, if the provided args and kwargs are equal (by value) to the cached arguments, return the cached result without calling func again. - If the arguments differ, call func again and update the cache accordingly. Notes: - Argument comparison must be by value. Use deep copies when storing cached args/kwargs so later mutations to passed objects do not change the stored snapshot. - The wrapper should accept any args and kwargs and forward them to func.

Task

Implement a function factory cache_last(func) that returns a wrapper which caches only the most recent call (arguments and result). The cache should compare arguments by value (not by identity) so mutations after a call don't incorrectly affect the cached snapshot.

Examples

Basic usage

Input

def add(a, b): print('calculating') return a + b cached_add = cache_last(add) cached_add(2, 3) cached_add(2, 3)

Output

first call returns 5 and prints 'calculating'; second call returns 5 with no additional print

The first call computes and caches the result. The second identical call returns the cached result without invoking add again.

Input format

The grader will execute your module and then evaluate test helper functions (no console input). Your implementation must provide cache_last(func). Test helpers included call cache_last with various argument patterns.

Output format

Each test expression evaluated by the harness must return a value; the harness compares str(value) to the expected string.

Constraints

Do not use external libraries. Use copy.deepcopy for safe value-based caching. The cache only needs to remember the last call (not multiple entries).

Samples

Sample 1

Input

cached = cache_last(lambda x: x*10) cached(3) cached(3)

Output

first call returns 30, second returns 30 from cache

The sample shows a simple function cached for repeated identical calls.