Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Accumulative list
#1
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
Reply
#2
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]
Reply
#3
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020