Supplementing the std lib (Was: partial sums problem)

Ian Kelly ian.g.kelly at gmail.com
Thu Sep 30 04:17:46 CEST 2010


On Wed, Sep 29, 2010 at 7:06 PM, Paul Rubin <no.email at nospam.invalid> wrote:

> As for the stdlib, the natural places for such a function would be
> either itertools or functools, and the function should probably be called
> "scan", inspired by this:
>
>  http://en.wikibooks.org/wiki/Haskell/List_processing#Scans
>
> Python's version would be like "scanl" with an optional arg to make it
> like "scanl1".
>

Something like this?

NoInitialValue = object()

def scan(function, iterable, initial=NoInitialValue):
    iterator = iter(iterable)

    if initial is NoInitialValue:
        try:
            accumulator = iterator.next()
        except StopIteration:
            return
    else:
        accumulator = initial

    yield accumulator

    for arg in iterator:
        accumulator = function(accumulator, arg)
        yield accumulator

Cheers,
Ian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100929/dc971f4a/attachment.html>


More information about the Python-list mailing list