maximum() efficency
Steven Bethard
steven.bethard at gmail.com
Sun Mar 26 19:36:42 EST 2006
Steve R. Hastings wrote:
> On Sun, 26 Mar 2006 10:34:16 -0700, Steven Bethard wrote:
>> What's the original?
>
> def minimum(cmp, lst):
> """minimum(cmp, lst)
>
> Returns the minimal element in non-empty list LST with elements
> compared via CMP() which should return values with the same semantics
> as Python's cmp(). If there are several minimal elements, the last
> one is returned.
> """
>
> if not lst:
> raise ValueError, 'empty list'
>
> minval = lst[0]
>
> for i in xrange(1, len(lst)):
> v = lst[i]
> if cmp(minval, v) > 0:
> minval = v
>
> return minval
>
> This is from Google's "goopy" package.
>
> http://goog-goopy.sourceforge.net/
Ahh. Yeah, nasty cmp= arguments certainly do screw that up.
If you're not just trying to implement a particular API, and you
actually have a use-case you think you need this for, you might consider
a key= argument instead of a cmp= argument. It'll probably be at least
as fast, and Python 2.5 will have one on both min() and max(). It'll
work something like:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/389659
STeVe
More information about the Python-list
mailing list