General sort() function?

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Dec 18 04:34:02 EST 2002


"James T. Dennis" <jadestar at idiom.com> wrote in
news:1040175290.16506 at smirk: 

>  It seems like we frequently want to have a sort() function that
>  returns a *copy* of an arbitrary sequence in a sorted order.
> 
I don't remember ever having that as a requirement. I sometimes want to 
have a sorted copy of a list, or list that is a sorted copy of some other 
sequence type, or a sorted sequence of a known type.

>  Are there any sequence types I'm missing?  Are their odd corner cases
>  I'm failing to consider (particularly in the copying)?
> 
How about (untested code):

import copy, types
def sort(sequence):
    # Directly sortable, simply copy sort and return
    if hasattr(sequence, 'sort'):
        duplicate = copy.copy(sequence)
        duplicate.sort()
        return duplicate

    # Convert to list, sort then convert back
    duplicate = list(sequence)
    duplicate.sort()

    factory = type(sequence)
    if isinstance(sequence, types.StringTypes):
        factory = factory('').join
    return factory(duplicate)

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list