Help us understand the problem. What is going on with this article?

reduceList(reduce の途中経過をリスト出力)

More than 1 year has passed since last update.

こんにちは
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]
kkdd
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away