Python accumulator list

2

I'm developing a function that takes 3 parameters fctn (function, list, element) and you have to return a list with the intermediate states of the accumulator, as in the example below:

>>> fctn(lambda acc, x: acc + x, [1, 2, 3, 4], 0) 
[0, 1, 3, 5,7]

My code:

def fctn(function, list, element):

acc = elem

for x in list: 
    list = map(lambda acc: lambda x: acc + x, l)

return list

But it does not return what I intend ...

    
asked by anonymous 09.04.2017 / 17:42

2 answers

3

See what you see:

import functools

# Utilizando Funcoes de alta ordem
def acumulator(n,dt):
    current = n+dt['last']
    dt['ac'].append(current)
    dt['last'] = n

data = {'last': 0, 'ac': []}
list(map(lambda n: acumulator(n, data), [n for n in range(0,5)]))

print ('Acumuladores => ',data['ac'])
Acumuladores =>  [0, 1, 3, 5, 7]

DEMO

    
09.04.2017 / 23:20
0

According to the statement, I expected a different result: the list of partial cumulative sums.

Suggest a recursive definition:

def fctn(f,l,n):
  if not l: 
     return [n]
  else: 
     return [n]+fctn(f,l[1:], f(n,l[0]))

that is:

>>> fctn(lambda acc, x: acc + x, [1, 2, 3, 4], 0)
[0, 1, 3, 6, 10]
    
16.05.2017 / 16:19