best cumulative sum

bonono at gmail.com bonono at gmail.com
Wed Nov 23 16:31:56 CET 2005


David Isaac wrote:
> > Michael Spencer wrote:
> > > This can be written more concisely as a generator:
>
>
> <bonono at gmail.com> wrote in message
> news:1132708265.941224.186550 at g44g2000cwa.googlegroups.com...
> > If iterable has no elements, I believe the behaviour should be [init],
> > there is also the case of init=None that needs to be handled.
>
> Right.  So it is "more concise" only by being incomplete, right?
> What other advantages might it have?
>
> > otherwise, that is more or less what I wrote for my scanl/scanl1.
>
> I didn't see a post with that code.
>
> Alan Isaac

def scanl1(func, seq):
    def my_func(x):
        my_func.init = func(my_func.init, x)
        return my_func.init

    i = iter(seq)
    try: my_func.init = i.next()
    except StopIteration: return []

    return (chain([my_func.init], (my_func(y) for y in i)))

def scanl(func, seq, init):
    def my_func(x):
        my_func.init = func(my_func.init, x)
        return my_func.init

    my_func.init = init
    return (chain([my_func.init], (my_func(y) for y in seq)))




More information about the Python-list mailing list