best cumulative sum

Gerard Flanagan grflanagan at yahoo.co.uk
Tue Nov 22 06:46:57 EST 2005


David Isaac wrote:

> What's the good way to produce a cumulative sum?
> E.g., given the list x,
> cumx = x[:]
> for i in range(1,len(x)):
>  cumx[i] = cumx[i]+cumx[i-1]
>
> What's the better way?
>
> Thanks,
> Alan Isaac

Don't know about better, but this is what I came up with:


class PartialSum(object):
    def __init__(self, alist):
        self.sequence = alist[:]
        self.N = len(alist)
        self.reset()

    def reset(self):
        self._i = 0
        self._sumi = 0

    def __iter__(self):
        return self

    def next(self):
        if self._i == self.N:
            self.reset()
            raise StopIteration
        self._sumi += self.sequence[self._i]
        self._i += 1
        return self._sumi


for sum in PartialSum( [1,1,1,1,1] ):
    print sum **2

1
4
9
16
25

Gerard




More information about the Python-list mailing list