Sort documentation inaccurate?
Bruce Dawson
comments at cygnus-software.com
Thu Sep 27 08:21:50 CEST 2001
I think I pointed out in the original post that the tooltip for
PythonWin says that the return value is -1, 0. This is inconsistent
with the other documentation. One of them is wrong.
There is some indication that the tooltip might actually be correct -
since returning just 0 and -1 works perfectly.
If any negative number is allowed then the documentation should
say that - otherwise anybody who returns (x - y) is breaking
the rules and writing ill-defined code.
David Glasser wrote:
> Bruce Dawson <comments at cygnus-software.com> wrote:
>
> > >>> mylist = [1, 2, 3, 5, 4, 6]
> > >>> def compare1(x, y):
> > ... return x < y
> > ...
> > >>> mylist.sort(compare1)
> > >>> mylist
> > [1, 2, 3, 5, 4, 6]
>
> The comparison "x < y" can return two values: 1 if x < y, and 0 if
> x >= y. But a sort function really needs to be more specific,
Know it doesn't. You can do a sort with just less than.
>
> differentiating between x < y, x > y, and x == y. The standard for sort
is moving towards a two value return. This allows sorting with just a
single operator that returns true or false. The STL in C++ uses this.
In fact, returning just 0/1 leads to a faster sort than returning -1/0/1
>
> functions, based on C's strcmp, is to return:
>
> -1 if x < y
> 0 if x == y
> +1 if x > y
>
> (It appears that any negative value is as good as -1, and any positive
> for +1, but the documentation just say those specific values.) This is,
> as you said, so a function can do something along the lines of "return x
> - y".
>
> The really good news, though, is that you can ignore most of this by
> using Python's cmp function. For example, to sort by absolute value:
>
> >>> x = [1, 0, -2, 52, -32, 4]
> >>> def abssort(x, y):
> ... return cmp(abs(x), abs(y))
> ...
Interesting. I'll have to try the cmp function. However according to the
documentation it is not guaranteed that cmp() will work with sort. cmp
returns negative, zero, or postive. The documentation clearly says that
sort expects -1, 0 or 1.
I'm not trying to be annoyingly fussy, I just hate using undefined
behaviour.
>
> >>> x.sort(abssort)
> >>> x
> [0, 1, -2, 4, -32, 52]
>
> --
> David Glasser
> news at davidglasser.net http://www.davidglasser.net/
More information about the Python-list
mailing list