[Python-ideas] Add nullifier argument to functools.reduce?
Peter Otten
__peter__ at web.de
Sun Aug 24 14:35:57 CEST 2014
David Mertz wrote:
> def reduce_with_attractor(func, it, start=None, end_if=None):
> it = iter(it)
> start = start if start!=None else it.__next__()
> return list(takewhile(lambda x: x!=end_if,
> accumulate(chain([start],it), func)))[-1]
Wouldn't it be better to break this into a function that limits a sequence
and to combine that with the original reduce()?
>>> from functools import reduce
>>> from itertools import takewhile
>>> def stop_on(value, items):
... return takewhile(lambda item: item != value, items)
...
>>> list(stop_on(0, [1, 2, 3, 0, 4]))
[1, 2, 3]
>>> from operator import mul
>>> reduce(mul, stop_on(0, [1, 2, 3, 0, 4]))
6
My suggestion is to add a value-limited version of itertools.takewhile()
rather than making reduce() more more powerful/complex.
More information about the Python-ideas
mailing list