[Python-ideas] Make max() stable

אלעזר elazarg at gmail.com
Fri Jan 17 14:45:14 CET 2014


Hi all,

Given several objects with the same key, max() returns the first one:

    >>> key = lambda x: 0
    >>> max(1, 2, key=key)
    1

This means it is not stable, at least according to the definition in
"Elements of Programming" by Alexander Stepanov and Paul McJones (pg. 52):

"Informally, an algorithm is stable if it respects the original order of
equivalent objects. So if we think of minimum and maximum as selecting,
respectively, the smallest and the second smallest from a list of two
arguments, stability requires that when called with equivalent elements,
minimum should return the first and maximum should return the second."

A page later, In a side note, the authors mention that "STL incorrectly
requires that `max(a, b)` return `a` when `a` and `b` are equivalent." (As
a reminder, Stepanov is the chief designer of the STL).

So, I know this is not a big issue, to say the least, but is there any
reason *not* to return the last argument? Are we trying to be compatible
with STL somehow?

I admit I don't know of any real use case where this really matters, but I
can point out that

   >>> ab = (1, 2)
   >>> (min(ab, key=key), max(ab, key=key))
   (1, 1)

is visibly less sensible than (1, 2).

Hope I'm not being a crank here...

Elazar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140117/00d1ee4f/attachment.html>


More information about the Python-ideas mailing list