best cumulative sum
Bengt Richter
bokr at oz.net
Mon Nov 21 18:32:55 EST 2005
On Mon, 21 Nov 2005 15:23:20 +1100, Steven D'Aprano <steve at REMOVEMEcyber.com.au> wrote:
>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.
I think x[:] ought to be a faster space allocation than building by appending,
but I think there is too much indexing in the OP's version,
so I think I would combine ideas, e.g.,
# (still ;-) untested
def cumulative_sum(L):
CL = L[:]
csum = 0
for i, x in enumerate(L):
csum += x
CL[i] = csum
return CL
I minor nit might be in how/when promotions to long or float happen if L has
mixed types. The OP didn't mention any requirements, but e.g. his version won't ever
promote the first output element, since he walks replacements from L[1] on.
( posting delayed >12 hrs due to news server prob ;-/ )
Regards,
Bengt Richter
More information about the Python-list
mailing list