1

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 :)

user2662833
  • 1,005
  • 1
  • 10
  • 20
  • 1
    Have you looked at `itertools` functions? One of them does exactly this. – vaultah Dec 07 '16 at 10:51
  • 1
    This is called a *cumulative sum*. Try `np.cumsum(x)` for instance. Probably a dupe of this http://stackoverflow.com/questions/15889131/how-to-find-the-cumulative-sum-of-numbers-in-a-list – David Arenburg Dec 07 '16 at 10:52
  • Relevant: http://stackoverflow.com/questions/40009019/python-recursive-sum-list – Chris_Rands Dec 07 '16 at 10:57
  • Well, sum is just a pathological example :P I'm trying to achieve this with a very different function. – user2662833 Dec 07 '16 at 11:05

1 Answers1

0

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)
SerialDev
  • 2,777
  • 20
  • 34