best cumulative sum

David Isaac aisaac0 at verizon.net
Wed Nov 23 11:38:24 EST 2005


"Michael Spencer" <mahs at telcopartners.com> wrote in message
news:mailman.1054.1132707811.18701.python-> This can be written more
concisely as a generator:
>
>   >>> import operator
>   >>> def ireduce(func, iterable, init):
>   ...     for i in iterable:
>   ...         init = func(init, i)
>   ...         yield init

OK, this might do it.  But is a generator "better"?
(I assume accuracy is the same, so what about speed?)

def ireduce(func, iterable, init=None):
    if not init:
        iterable = iter(iterable)
        init = iterable.next()
        yield init
    elif not iterable:
        yield init
    for item in iterable:
         init = func(init, item)
        yield init

Alan Isaac





More information about the Python-list mailing list