Practice: functools
Q1. Product of a list
Use reduce to print the product of [1, 2, 3, 4, 5].
Goal: Use reduce.
Q2. Longest word
Use reduce to find the longest word in ['sun', 'planet', 'moon'] and print it.
Goal: Use reduce.
Q3. Double function
Use partial with the function multiply(a, b) to make double, and print double(21).
Goal: Use partial.
Q4. Cache a square
Write a cached function square(n) and call it twice with 4. Print the hit count from cache_info().
Goal: Use lru_cache.
Q5. Decorator with wraps
Write a decorator twice that calls a function twice, using wraps. Decorate hello() that prints 'hi' and print hello.__name__ after calling it.
Goal: Use wraps.
Q6. Reduce with initial
What does this print?
from functools import reduce
print(reduce(lambda a, b: a + b, [1, 2, 3], 100))Goal: reduce initial.
Q7. partial keyword
What does this print?
from functools import partial
def greet(greeting, name):
return f'{greeting}, {name}!'
hi = partial(greet, 'Hi')
print(hi('Ana'))Goal: partial positional.
Q8. Cache calls
What does this print?
from functools import lru_cache
@lru_cache(maxsize=None)
def f(x):
print('working')
return x + 1
print(f(1))
print(f(1))Goal: Cache behaviour.
Q9. Name without wraps
What does this print?
def deco(func):
def wrapper():
return func()
return wrapper
@deco
def task():
return 1
print(task.__name__)Goal: wraps purpose.
Q10. singledispatch
What does this print?
from functools import singledispatch
@singledispatch
def kind(x):
return 'other'
@kind.register(str)
def _(x):
return 'text'
print(kind('a'), kind(3))Goal: singledispatch.
Q11. Sorting with cmp_to_key
What does this print?
from functools import cmp_to_key
def compare(a, b):
return b - a
print(sorted([3, 1, 2], key=cmp_to_key(compare)))Goal: cmp_to_key.
Q12. Fix the decorator
This decorator hides the real name and docstring. Fix it so print(add.__name__) shows add.
def log(func):
def wrapper(*a, **k):
return func(*a, **k)
return wrapper
@log
def add(a, b):
return a + b
print(add.__name__)Goal: Use wraps.
Q13. Fix the unhashable cache
This cached function fails when given a list. Fix it by passing a tuple.
from functools import lru_cache
@lru_cache(maxsize=None)
def total(items):
return sum(items)
print(total([1, 2, 3]))Goal: Hashable arguments.
Q14. Why reduce initial
Why is it safer to give reduce an initial value?
Goal: reduce safety.
Q15. When not to cache
Name one kind of function that you should not decorate with lru_cache.
Goal: Pure functions.
Q16. Price with tax
Use partial to make add_tax from price_with(rate, price) with rate 0.1. Print add_tax(200) as a number with one decimal.
Goal: Use partial in real tasks.
Q17. Merge dictionaries
Use reduce to merge [{'a': 1}, {'b': 2}, {'a': 3}] into one dict and print it.
Goal: Use reduce to merge.