[Python-ideas] Make max() stable

Tim Peters tim.peters at gmail.com
Sat Jan 18 06:37:28 CET 2014


[אלעזר <elazarg at gmail.com>]
> 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 sound argument, provided one accepts the "if".  But nobody in the
known history of the world *does* think of min and max that way
outside this silly quote ;-)

> 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?

No.  We're just doing what everyone *really* expects min and max to do
- including whoever implemented the STL's max().

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

One removed from being a crank is not itself being a crank :-)


More information about the Python-ideas mailing list