[CentralOH] 2014-11-14 道場 Scribbles: running_* --> toolz.accumulate

jep200404 at columbus.rr.com jep200404 at columbus.rr.com
Wed Feb 25 16:29:05 CET 2015


On Mon, 17 Nov 2014 09:55:41 -0500, jep200404 at columbus.rr.com wrote:

> def running_op(iterable, op=operator.add, initial=0):
>     running_result = initial
>     for element in iterable:
>         running_result = op(running_result, element)
>         yield running_result
> 
> def running_sum(iterable, initial=0):
>     sum_ = initial
>     for element in iterable:
>         sum_ += element
>         yield sum_

Compare those with toolz.accumulate().

import toolz
from operator import add, mul
print list(toolz.accumulate(add, [1, 2, 3, 4, 5]))
print list(toolz.accumulate(mul, [1, 2, 3, 4, 5]))
print reduce(add, [1, 2, 3, 4, 5])
print reduce(mul, [1, 2, 3, 4, 5])

http://colug.net/python/cohpy/20131029/


More information about the CentralOH mailing list