Python - PyDash example of reduce with accumulator

Viewed 113

Looking for a code example using Python’s PyDash module of reduce with the accumulator arg, and how to output that with previous and current.

1 Answers

pydash.reduce_ is not very different from the built-in functools.reduce.

A good example for using the accumulator (or the initial parameter in functools' case) is to use it as a "neutral element":

def factorial(n):
    return pydash.reduce_(range(1, n), lambda total, x: total*x, accumulator=1)

In this case, 1 is used as the initial value and doesn't affect the result (since 1*x=x), but more importantly: It will be used as the return value if there are no elements in range(1, n).

And indeed, factorial(0) == factorial(1) == 1 is the required result.

Related