こんにちは
reduceList
を作ってみました(Python)。reduce
の処理経過をリスト出力するもので、itertools.accumulate
と同じ動作となります。試した関数は二項の和です(sum_f
)。
>>> import functools, itertools
>>> def reduceList(f, arr, init=None):
>>> if init is None:
>>> init = arr.pop(0)
>>> return functools.reduce(lambda x, y: x + [f(x[-1], y)], arr, [init])
>>>
>>> sum_f = lambda x, y: x + y
>>>
>>> functools.reduce(sum_f, range(1, 5))
10
>>> list(itertools.accumulate(range(1, 5), sum_f))
[1, 3, 6, 10]
>>> reduceList(sum_f, range(1, 5))
[1, 3, 6, 10]
>>> reduceList(sum_f, range(1, 5), 0)
[0, 1, 3, 6, 10]