[Python-ideas] Make max() stable
Ned Batchelder
ned at nedbatchelder.com
Sat Jan 18 02:35:57 CET 2014
On 1/17/14 8:45 AM, אלעזר wrote:
> 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."
I don't understand this logic at all. Stability matters in sorting
because sort() takes a sequence and returns a sequence, and for various
reasons you might need to sort a list twice, with different criteria.
Stability guarantees that the second sort won't discard the work of the
first sort.
Is there an example of an actual problem that stability of min and max
would make easier to solve?
--Ned.
More information about the Python-ideas
mailing list