How to sum elements along a functional path

I am trying to write a function that displays elements of a list in order to get the sum of an element and previous elements in a list in a functional style using python, for example:

func([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) = [0, 1, 3, 6, 10, 15, 21, 28, 36, 45] 

I tried using recursion, but I get RuntimeError: maximum recursion depth exceeded with a long list .:

 def recursion_way(inlist, accu, summ): if len(inlist) == 0: return accu else: return recursion_way(inlist[1:], accu + [summ + inlist[0]], summ + inlist[0]) 
+4
source share
6 answers

Is understanding taken into account?

 >>> [sum(l[:i]) for i, _ in enumerate(l)] [0, 0, 1, 3, 6, 10, 15, 21, 28, 36] 

or possibly using reduce :

 reduce( lambda (sums, last), x: (sums+[x+last], x+last), l, ([], 0) )[0] 

Or in another way:

 reduce(lambda sums,x: sums+[x+sums[-1]], l[1:], l[:1]) 
+6
source

Here is the cumulative sum made in the style of functional programming:

 def func(l): if len(l) < 2: return l sub = func(l[:-1]) return sub + [sub[-1] + l[-1]] print func([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 
+1
source

How about a cut? Slow but interesting, imo.

 def func(p): for i in xrange(1, len(p)+1): yield reduce(lambda x, y: x + y, p[0:i]) >>> list(func(p)) [0, 1, 3, 6, 10, 15, 21, 28, 36, 45] 
+1
source

Here is what I got using recursion:

 def f(L, n=0): # If the list is empty, that means we went through all the elements there if len(L)>0: # n is the last element in the sum list. Add to it the first remaining element n = n+L[0] # Return a list containing the newest item and those of the remaining elements return [n] + f(L[1:], n) else: # It it is empty, there are no more sums to calculate return [] 
+1
source

Can you use numpy?

 import numpy numpy.cumsum([0,1,2,3,4,5,6,7,8,9]) array([ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45]) 
0
source
 l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] reduce(lambda x, y: x+y, l) 
-2
source

All Articles