reduce and partial in Python
Two functools staples: folding and pre-filling arguments.
from functools import reduce, partial
product = reduce(lambda acc, n: acc * n, [1, 2, 3, 4], 1)
running = reduce(lambda acc, n: acc + [acc[-1] + n], [1, 2, 3], [0])
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
nine = square(3)
How it works
reducefolds a sequence into one value.partialfixes an argument to make a new function.squareandcubespecialize onepower.
Keywords and builtins used here
deflambdapowerreturn
The run, in numbers
- Lines
- 13
- Characters to type
- 307
- Tokens
- 103
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 59 seconds.
Step 5 of 5 in Generators & itertools, step 14 of 53 in Pythonic Python.