Skip to content
Foxipa
Code Completion 4 Challenges

Complete the function-caching code

Practice caching deterministic results, limiting stored entries, clearing stale data, and inspecting cache hits.

Intermediate ~8 min read

Challenge 1

Return a normalized label so repeated calls with the same raw string can reuse the cached result.

python Your answer
from functools import cache

@cache
def display_name(raw):
    

print(display_name("  FOX IPA "))
print(display_name("  FOX IPA "))

Press Ctrl⌘Enter to check your answer

Challenge 2

Complete the lookup body. The decorator already limits the cache to two recent entries.

python Your answer
from functools import lru_cache

fees = {"near": 3.0, "mid": 5.0, "far": 8.0}

@lru_cache(maxsize=2)
def delivery_fee(zone):
    

for zone in ("near", "mid", "near", "far"):
    print(delivery_fee(zone))
print(delivery_fee.cache_info().maxsize)

Press Ctrl⌘Enter to check your answer

Challenge 3

Clear the old cached result after the backing mapping changes.

python Your answer
from functools import cache

stock = {"bread": 4}

@cache
def available(item):
    return stock[item]

print(available("bread"))
stock["bread"] = 7
available.cache_()
print(available("bread"))

Press Ctrl⌘Enter to check your answer

Challenge 4

Print the number of cache hits after repeating the same call.

python Your answer
from functools import lru_cache

@lru_cache(maxsize=4)
def double(number):
    return number * 2

double(6)
double(6)
print()

Press Ctrl⌘Enter to check your answer