Codzy

Functional programming

Functional programming builds a program out of pure functions: they always return the same result for the same arguments and don't change anything outside themselves. You avoid modifying data and create new data instead. map(), filter() and comprehensions follow this idea.

The functools module brings powerful tools: reduce() combines all the items into a single value, partial() creates a function with some arguments already filled in, and @lru_cache remembers a function's results so it doesn't compute them again.

from functools import reduce, partial, lru_cache

numbers = [1, 2, 3, 4]
print(reduce(lambda acc, n: acc + n, numbers, 0))

def power(base, exp):
    return base ** exp

square = partial(power, exp=2)
print(square(9))

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

print(fib(30))

Start the lesson