partial list sort

Alex Martelli aleax at aleax.it
Fri Oct 11 04:26:53 EDT 2002


Manuel M. Garcia wrote:

> On Thu, 10 Oct 2002 10:10:44 GMT, Alex Martelli <aleax at aleax.it>
> wrote:
> 
>>Here's my suggestion (untested):
>>def jsaulsort(alist):
>>    aux = [ (i%3, alist[i][1], alist[i]) for i in range(len(alist)) ]
>>    aux.sort()
>>    alist[:] = [ item[2] for item in aux ]
> 
> This is the best one yet!  One little bug, you meant to use the
> integer divide "//" instead of modulo "%".

Yes, sorry, you're right -- I _did_ indeed mean // (I'll write out
a hundred times in longhand "it's not enough to say 'untested', I
MUST test"...).


> Python code should strive for clarity and consistency.  And the
> Decorate - Sort - Undecorate (DSU) technique is clear and applicable
> over a wide range of custom sorts.

Yep!  The main exception, as pointed out in followups, are sorts
that need to be ascending on some keys, descending on other keys,
when the latter keys are not necessarily numbers -- unfortunately
there's no way to write a hypothetical function F such that for
all X and Y over some very wide domains including non-numbers:

    cmp(F(X), F(Y)) == cmp(Y, X)

alas...


Alex




More information about the Python-list mailing list