is this sort method the same as the one in python 2.4

Lowell Kirsh lkirsh at cs.ubc.ca
Sat Jan 29 21:35:04 EST 2005


I'm trying to emulate the sorted() method introduced in python 2.4. The 
only difference is that it takes a sequence as one of its arguments 
rather than being a method of the sequence class. Does my method do the 
same as the sorted()? The obvious difference is that my method is called 
as sort(seq, cmp, key, reverse) rather than seq.sorted(cmp, key, reverse)

def sort(seq, cmp=None, key=None, reverse=False):
     "return a sorted copy of its input"
     if sys.version_info > (2,4):
         return sorted(seq, cmp, key, reverse)
     if key:
         toreturn = [ (key(elt), elt) for elt in seq ]
     else:
         toreturn = seq[:]
     if cmp:
         toreturn.sort(cmp)
     else:
         toreturn.sort()
     if key:
         toreturn = [ b for (a,b) in toreturn ]
     if reverse:
         toreturn.reverse()
     return toreturn


Lowell



More information about the Python-list mailing list