LoginSignup
0
0

More than 3 years have passed since last update.

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

Last updated at Posted at 2019-07-18

こんにちは
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]
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0