best cumulative sum
Steven D'Aprano
steve at REMOVEMEcyber.com.au
Sun Nov 20 23:23:20 EST 2005
David (Alan) 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?
Is there something that this doesn't do, or something
it does do that it shouldn't?
You could do it this way:
# untested
def cumulative_sum(L):
CL = []
csum = 0
for x in L:
csum += x
CL.append(csum)
return CL
Whether it is better or worse depends on what you
consider better or worse.
--
Steven.
More information about the Python-list
mailing list