functools Module
The functools module provides higher-order functions
that enhance and optimize function behavior.
functools.reduce()
from functools import reduce
nums = [1, 2, 3, 4]
result = reduce(lambda a, b: a + b, nums)
print(result)
functools.partial()
from functools import partial
def power(base, exp):
return base ** exp
square = partial(power, exp=2)
print(square(5))
functools.lru_cache()
Caches function results to improve performance.
from functools import lru_cache
@lru_cache()
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
print(fib(10))
💡 lru_cache is commonly used in recursion & optimization.
📝 Practice: Use
lru_cache to optimize factorial.