Search code examples
pythonreducepython-itertools

Combining map and reduce


I want to find a neat way to achieve the following:

Pretend I have a list:

> x = [1, 2, 3, 4, 5]

And a simple function that just adds two numbers:

> def add(a, b)
      return a+b

I can reduce the list x directly with:

> sum = reduce(add, x)
> print(sum)
15

Which gives me the sum just fine. But I would like to know the value after each application of add. So using a function similar to reduce, I'd like to get back the following array:

> result = SOME_FUNCTION(add, x)
> print(result)
[3, 6, 10, 15]

Does anybody have a cool way of achieving that. I have a strong preference for using some form of itertools solution if possible :)


Solution

  • Since you want itertools

    from itertools import accumulate
    list(accumulate(x))
    Out [130]:
    [1, 3, 6, 10, 15]
    

    Alternatively a generator loop

    def cumsum(x):
        total = 0
        for x in it:
            total += x
            yield total
    list(cumsum(x))
    Out [129]:
    [1, 3, 6, 10, 15]
    

    Or simply as David mentioned:

    np.cumsum(x)
    Out [123]:
    array([ 1,  3,  6, 10, 15], dtype=int32)