Python Forum
Accumulative list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Accumulative list (/thread-2780.html)



Accumulative list - py7 - Apr-09-2017

I need some help in a function that I am developing
It's a function that receives three parameters a function, a list and an element and returns a list with the intermediate states of the accumulator

like this: 
>>> fctn(lambda acc, x: acc + x, [1, 2, 3, 4], 0) 
[0, 1, 3, 5,7]
I have this: 
def ex(f, l, elem):
for x in l: 
    l = map(f(elem, x), l)
return l
 
but it's not what I want and return an error

if someone could help me


RE: Accumulative list - zivoni - Apr-09-2017

From your description it looks like you want to do a "running sum" (but your example result doesnt correspond with running sum ...), that can be done with itertools.accumulate()

Output:
In [1]: from itertools import accumulate In [2]: list(accumulate([1,2,3,4], lambda x, y: x+y))  # default function is adding, so it would work just with list ... Out[2]: [1, 3, 6, 10] In [3]: list(accumulate([1,2,3,4], lambda x, y: x*y)) Out[3]: [1, 2, 6, 24] In [4]: list(accumulate([0,1,2,3,4], lambda x, y: x+y))  # If you need start value, put it as first element Out[4]: [0, 1, 3, 6, 10]
You can implement your own accumulate-like function with repeatedly applying function and either appending result to a list or yielding it:
def interstate(func, my_list, start):
    result = start
    yield result
    for element in my_list:
        result = func(result, element)
        yield result
Output:
In [9]: list(interstate(lambda x,y: x+y, [1,2,3,4], 0)) Out[9]: [0, 1, 3, 6, 10]



RE: Accumulative list - ichabod801 - Apr-09-2017

I thought the problem was to make something like a generalized Fibonacci sequence:
def fib_like(func, seq, start):
    result = [start]
    for item in seq:
        result.append(func(start, item))
        start = item
    return result
That at least gives the sample results that were posted.