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 lbut 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() 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
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 resultThat at least gives the sample results that were posted. |