Aug-01-2017, 08:30 PM
Functools is built into python: https://docs.python.org/3/library/functools.html
Reduce (other languages call it
That same snippet, spread out a bit, would look like this:
Reduce (other languages call it
fold
) takes a callable (normally a function), and applies it to two elements from a collection of things repeatedly until there's only one thing left. ie, it Reduces a collection of things into a single thing. https://docs.python.org/3/library/functo...ols.reduceThat same snippet, spread out a bit, would look like this:
>>> # the same as lambda x, y: x*y >>> def multiply(x, y): ... return x * y ... >>> fact = 4 >>> items = range(1, fact+1) >>> # set the starting value to whatever the first element of items is (...hint, it's "1") >>> answer = next(items) >>> # iterate over the rest of the range (2, 3, 4) and multiply them together >>> for num in items: ... answer = multiply(answer, num) ... >>> answer 24