Accumulate function in python

dhruvbird dhruvbird at gmail.com
Mon Jul 19 12:56:03 EDT 2010


On Jul 19, 9:12 pm, Brian Victor <homeusen... at brianhv.org> wrote:
> 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.
>
> Now that Steven's given you the simple, pythonic way, I'll just mention
> the advanced, complicated and obscure way that might be vaguely familiar
> if you're coming from a functional programming background:
>
> x = [ 0, 1, 2, 1, 1, 0, 0, 2, 3 ]
> def running_sum(result, current_value):
>     return result + [result[-1]+current_value if result else current_value]
>
> reduce(running_sum, x, [])
>
> Having offered this, I don't recall ever seeing reduce used in real
> python code, and explicit iteration is almost always preferred.

Yes, even I have noticed that reduce is a tad under-used function.

So, I guess no function like "accumulate" below exists in the standard
lib.


def accumulate(proc, seed, seq):
	ret = []
	for i in seq:
		ret.append(proc(seed, i))
	return ret

x = [0, 1, 3, 4, 5, 5, 5, 7, 10]
print accumulate(lambda x,y: x+y, 0, x)

My guess is that accumulate can be used in many more scenarios.

Regards,
-Dhruv.



More information about the Python-list mailing list