← All lessons

functools: lru_cache and reduce

Sign in · Sign up

Lesson 11.11

functools helps make code faster and shorter:

from functools import lru_cache, reduce

@lru_cache
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(30))                              # 832040
print(reduce(lambda a, b: a + b, [1, 2, 3]))  # 6
  • @lru_cache remembers the result: a second call with the same argument comes from the cache;
  • the cache only works with immutable arguments (numbers, strings);
  • reduce(func, list) folds the list into a single value, step by step.

The check sets the number n and the list nums. Print: fib(n), then fib(n) once more (it comes from the cache — the result is the same) and the sum of nums with reduce.

Hint

@lru_cache remembers the result for every n — a repeated call takes the ready one.

fib stays ordinary recursion with the base n < 2. For the sum of a list there is reduce with an addition function and the list.