2

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.

joe hoeller
  • 1,248
  • 12
  • 22

1 Answers1

3

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.

slallum
  • 2,161
  • 4
  • 24
  • 24