reduce()--what is it good for? (was: Re: reduce() anomaly?)

Francis Avila francisgavila at yahoo.com
Mon Nov 10 06:37:52 CET 2003


"Douglas Alan" <nessus at mit.edu> wrote in message
news:lcu15f72bq.fsf at gaffa.mit.edu...
> Alex Martelli <aleaxit at yahoo.com> writes:
>
> I agree: Down with bloat!  Get rid of sum() -- it's redundant with
> reduce(), which I use all the time, like so:
>
>      def longer(x, y):
>         if len(y) > len(x): return y
>         else: return x
>
>      def longest(seq):
>         return reduce(longer, seq)
>
>      print longest(("abc", "yumyum!", "hello", "goodbye", "?"))
>
>   => yumyum!
>
> |>oug

Oh, guys...

def ireduce(func, seq):
    seq = iter(seq)
    try:
        i = seq.next()
            while True:
                i = func(i, seq.next())
    except StopIteration:
        return i

def cond(boolean, iftrue, iffalse):
    if boolean: return iftrue
    else: return iffalse

>>> ireduce(lambda x, y: cond(len(x)==5, x,y), "All we are saying, is give
peace a chance!".split(' '))
'peace'

Can't we all just....get along?
--
Francis Avila





More information about the Python-list mailing list