Python accumulator list

Asked

Viewed 323 times

2

I am developing a function that takes 3 parameters fctn(Function, list, element) and that it has 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 don’t give back what I want...

  • The question is a little confused, try to demonstrate through a common function (without lambda) or even through pseudocode or table test.

  • Dude... I get it. It’s pretty much the same question I answered a few hours ago. I refactored the code to answer your question.

  • 1

    please post code with correct indentation

  • @py_9, According to your text, to be a accumulator with lambda acc, x: acc + x should not give the list of accumulated sums [0, 1, 3, 6, 10]?

2 answers

3


See if it answers:

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

0

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

I suggested 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 to say:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.