[Python-3000] what do I use in place of reduce?

Adam Olsen rhamph at gmail.com
Thu Apr 24 07:24:41 CEST 2008


On Wed, Apr 23, 2008 at 11:06 PM, Nicholas T <ntung at ntung.com> wrote:
> On Wed, Apr 23, 2008 at 9:08 PM, Alex Martelli <aleaxit at gmail.com> wrote:
>
> >
> > On Wed, Apr 23, 2008 at 6:47 PM, Guido van Rossum <guido at python.org>
> wrote:
> > > On Wed, Apr 23, 2008 at 1:56 PM, Nicholas T <ntung at ntung.com> wrote:
> > >
> > > >    It's obvious how to use LC's to replace map and filter, but what
> about
> > >  > reduce? It is one of my favorite functions.
> > >  >
> > >  > >>> time=1901248
> > >  > >>> reduce(lambda a, b: a[:-1] + [a[-1]%b, math.floor(a[-1]/b)],
> [[time],
> > >  > 60, 60, 24])
> > >  >  [28, 7.0, 0.0, 22.0] # secs, mins, hrs, days
> > >
> > >  I recommend learning how to use a good old for-loop. That example is
> > >  as cryptic as can be. It's also inefficient due to calling a function
> > >  for each iteration.
> >
> > I normally frown on "me too" posts, but this time I won't refrain from
> > a loud "hear, hear!". "Clever" code is NOT a culturally positive trait
> > in the Python community (differently from most language communities...
> > and this is in fact one reason I love Python).
> >
> > Alex
> >
>
> It wasn't only posted to be cryptic, it's one thing that's difficult to
> write with a for loop without a lot of verbosity (at least I couldn't figure
> out how to do it...).

>>> time = 1901248
>>> seconds = time % 60
>>> minutes = time // 60 % 60
>>> hours = time // 60 // 60 % 24
>>> days = time // 60 // 60 // 24
>>> seconds, minutes, hours, days
(28, 7, 0, 22)

Doesn't even need a loop.  Just don't try to be clever.  If you think
it's too verbose then put it in its own function (even if you only
call it in one place!)  The function itself will be quite readable and
so will the caller (so long as you pick a good name.)

-- 
Adam Olsen, aka Rhamphoryncus


More information about the Python-3000 mailing list