Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum elements in functional way

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])
like image 512
user1879805 Avatar asked Dec 05 '12 17:12

user1879805


2 Answers

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])
like image 127
Eric Avatar answered Sep 21 '22 01:09

Eric


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])
like image 29
NPE Avatar answered Sep 19 '22 01:09

NPE