Python's simplicity philosophy

David Eppstein eppstein at ics.uci.edu
Sun Nov 16 17:21:43 EST 2003


In article <KLRtb.2585$sb4.1651 at newsread2.news.pas.earthlink.net>,
 "Andrew Dalke" <adalke at mindspring.com> wrote:

> > >That would be max(seq, key=len) in my proposal.
> >
> > That's a nice option for max (and min, and ??), but ISTM that it would
> > also be nice to have a factory for efficient iterators of this kind.
> > It would probably be pretty efficient then to write
> >
> >     maxlen, maxitem = max(funumerate(len,seq))
> 
> With generator expressions this is
> 
>   maxlen, maxitem = max( ((len(x), x) for x in seq) )
> 
> It still has the (slight) problem that it assumes x is comparable
> when there are multiple items with the same length.  Nearly
> all of these quicky versions make that assumption.  The
> quicky will-work-for-any-item version would look more like
> 
>   maxlen, pos, maxitem = max( ((len(x), i, x) for i, x in enumerate(seq)) )

The new sort(key=...) option works even when the underlying objects are 
incomparable.  I'd expect the same of max(key=...)

So (supposing such a change ever happens) you could instead write
    maxitem = max(seq, key=len)
    maxlen = len(maxitem)

-- 
David Eppstein                      http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science




More information about the Python-list mailing list