Accumulate function in python

Andre Alexander Bell post at andre-bell.de
Mon Jul 19 10:24:41 EDT 2010


On 07/19/2010 01:18 PM, dhruvbird wrote:
> Hello,
>   I have a list of integers: x = [ 0, 1, 2, 1, 1, 0, 0, 2, 3 ]
>   And would like to compute the cumulative sum of all the integers
> from index zero into another array. So for the array above, I should
> get: [ 0, 1, 3, 4, 5, 5, 5, 7, 10 ]
>   What is the best way (or pythonic way) to get this.
> 
> Regards,
> -Dhruv.

Maybe not pythonic, but straight-forward:

>>> import numpy
>>> numpy.cumsum(x)
array([ 0,  1,  3,  4,  5,  5,  5,  7, 10])

An example with a class

class CumulativeSum(object):
    def __init__(self, start=0):
        self._current = start
    def __call__(self, value):
        self._current += value
        return self._current

>>> cummulative_sum = CumulativeSum(0)
>>> map(cummulative_sum, x)
[0, 1, 3, 4, 5, 5, 5, 7, 10]

Dirty:

current = 0

def cummulative_sum(value):
    global current
    current += value
    return current

>>> map(cummulative_sum, x)
[0, 1, 3, 4, 5, 5, 5, 7, 10]

Weird:

def cummulative_sum_reducer(x, y):
    x.append(x[-1] + y)
    return x

>>> reduce(cummulative_sum_reducer, x, [0])
[0, 0, 1, 3, 4, 5, 5, 5, 7, 10]

Cheers


Andre



More information about the Python-list mailing list