ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-list
python-list
Sort documentation inaccurate?
by Bruce Dawson other posts by this author
Sep 26 2001 6:03AM messages near this date
monitoring process creation on win32 (nt/w2k) | Re: Sort documentation inaccurate?
Or is it the implementation that is peculiar?

I'm using PythonWin 2.1 and I tried specifying a user compare function
to the list sort() function (so that I could sort file names based on
the numerical ordering instead of alphabetical) and I had difficulty
getting it working. I assumed without reading the docs carefully (if you
search the PythonWin docs for sort you get sparse information anyway)
that I could just return the result of a comparison, thusly:

> >> mylist = [1, 2, 3, 5, 4, 6]
> >> def compare1(x, y):
...  return x < y
...
> >> mylist.sort(compare1)
> >> mylist
[1, 2, 3, 5, 4, 6]

but it doesn't work. It leaves the list unchanged. Bummer.

A few days later (after writing a bubble sort - good thing I had a small
list) I was typing in PythonWin when the tooltip for sort() popped up
and it said that the return value for the compare function should be 0
or *negative* 1. So I tried this:

> >> mylist = [1, 2, 3, 5, 4, 6]
> >> def compare2(x, y):
...  return -(x < y)
...
> >> mylist.sort(compare2)
> >> mylist
[1, 2, 3, 4, 5, 6]

and it works!

On closer inspection the documentation says that the compare function is
supposed to return -1, 0 or 1. However this seems to be either
unnecessary, inaccurate, or both, since returning zero and one had no
effect, and returning 0 and -1 sorts the list perfectly.

Next time I'll have to read the docs more carefully, but somehow it
feels like this could be done better.

The behaviour certainly *feels* curious - having to return -(x < y) is a
trifle inelegant, and the 'correct' return value of:

if x >  y:
    return 1
return -(x < y

is cumbersome. In qsort() in the C library the preferred return method
is obviously something like:

return x - y;

but according to both sets of documentation that is illegal in Python,
since they specify -1, 0, 1 explicitly.

For what it's worth...


-- 
http://mail.python.org/mailman/listinfo/python-list
Thread:
Bruce Dawson
Bruce Dawson
Tim Peters
David Glasser
Sean 'Shaleh' Perry

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved