This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python functools, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
What does lru_cache do?
Answer: Caches results by argument values
Why: Repeated calls with the same arguments can reuse a stored result.
What does partial return?
Answer: A new callable with some arguments fixed
Why: partial stores arguments and waits for the remaining ones.
What does reduce do?
Answer: Folds an iterable into one value
Why: reduce applies a two-argument function cumulatively.
What does this code print?
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(5))Answer: 25
Why: partial fixes exponent to 2, so the call becomes power(5, 2).
Complete the cache decorator import.
from functools import ____Answer: lru_cache
Why: lru_cache is the memoization decorator in functools.
Complete the function that fixes an argument.
from functools import partial
def power(base, exponent):
return base ** exponent
square = ____(power, exponent=2)Answer: partial
Why: partial creates a specialized callable.
Complete the folding function.
from functools import reduce
print(____(lambda a, b: a + b, [1, 2, 3], 0))Answer: reduce
Why: reduce combines values from left to right.
Complete the cache size argument.
from functools import lru_cache
@lru_cache(____=None)
def square(n):
return n * nAnswer: maxsize
Why: maxsize=None lets the cache grow without a fixed limit.
What does the program output?
from functools import lru_cache
@lru_cache(maxsize=None)
def f(n):
return n * 2
print(f(2) + f(2))Answer: 8
Why: Both calls return four, so the sum is eight; the second call reuses the cached result.
What appears on the screen?
from functools import partial
def add(a, b):
return a + b
add5 = partial(add, 5)
print(add5(3))Answer: 8
Why: partial fixes the first argument to five, so the result is eight.
What is printed?
from functools import reduce
print(reduce(lambda a, b: a * b, [2, 3, 4]))Answer: 24
Why: The multiplication folds to twenty-four.
What is the output?
from functools import lru_cache
@lru_cache(maxsize=None)
def f(n):
return n + 1
f(1)
f(1)
print(f.cache_info().hits)Answer: 1
Why: The second call is a cache hit, so hits is one.
Try the questions first
Open the practice page for Python functools and answer the same 12 questions with instant feedback.