functools Module
partial, reduce, lru_cache
Interview Relevant: Functional utilities
functools
Tools for functional programming.
Code Examples
python
1from functools import reduce, partial, lru_cache
2
3# reduce
4product = reduce(lambda x, y: x * y, [1, 2, 3, 4]) # 24
5
6# partial
7def power(base, exp):
8 return base ** exp
9square = partial(power, exp=2)
10print(square(5)) # 25
11
12# lru_cache (memoization)
13@lru_cache(maxsize=None)
14def fib(n):
15 if n < 2: return n
16 return fib(n-1) + fib(n-2)