I am trying to write a function which maps elements of a list to get sum of the element and the previous elements in the list in a functional style using python e.g. :
func([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) = [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
I have tried using recursion, but 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])
Does a comprehension count?
>>> [sum(l[:i]) for i, _ in enumerate(l)]
[0, 0, 1, 3, 6, 10, 15, 21, 28, 36]
or perhaps using reduce
:
reduce(
lambda (sums, last), x: (sums+[x+last], x+last),
l, ([], 0)
)[0]
Or another way:
reduce(lambda sums,x: sums+[x+sums[-1]], l[1:], l[:1])
Here is cumulative sum done 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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With