sort descending on a[1], ascending on a[0]

Manuel M. Garcia mgarcia at cole-switches.com
Fri Oct 11 14:09:59 EDT 2002


On Fri, 11 Oct 2002 07:55:05 GMT, Alex Martelli <aleax at aleax.it>
wrote:

>def asc0desc1(a, b):
>    return cmp(a[0],b[0]) or cmp(b[1],a[1])

I forgot about this trick, but I think I might stick with
list1.sort(make_sort_f( [(2,-1),(1,-1),(0,1)] ))
in many situations because changing to different sort orders is
trivial, and with the proper sort I usually can continue working with
a much smaller beginning slice of the list, and of course with a
smaller list the speed up is dramatic for all operations.

>[alex at lancelot alex]$ python2.2 -O twoso.py
>1 1 1
>3.74 sortAdByMethod
>4.17 sortAdByDSUPasses
>2.74 sortAdByRichDSU
>[alex at lancelot alex]$ python2.3 -O twoso.py
>True True True
>0.97 sortAdByMethod
>2.75 sortAdByDSUPasses
>1.88 sortAdByRichDSU

>[alex at lancelot alex]$ python2.2 -O twoso.py
>1
>5.07 sortAdByMethod
>2.90 sortAdDSU
>[alex at lancelot alex]$ python2.3 -O twoso.py
>True
>1.39 sortAdByMethod
>1.31 sortAdDSU

Hooray for Python 2.3 and Tim Peters's sort()!  I will have to get
used to seeing "True" instead of "1"!

>The complicated approach
>of synthesizing 'decorated strings' whose comparison is the
>reverse than the original's, besides lack of generality (quite
>serious, btw -- it works here, but it will NOT work when two
>strings being compared can have the same prefix but with one 
>longer than the other!), is only a little faster than the simple
>minded "pass a comparison function" in 2.2

Yeah, and the strings I often end up working with are file paths,
which would be the worst case scenario for this technique



More information about the Python-list mailing list