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

Raymond Hettinger vze4rx4y at verizon.net
Sun Jan 30 00:25:52 EST 2005


"Lowell Kirsh"
> 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()?

Almost.  This is closer to the mark:

def sorted(iterable, cmp=None, key=None, reverse=False):
    "return a sorted copy of its input"
    if sys.version_info >= (2,4):
        return sorted(iterable, cmp, key, reverse)
    seq = list(iterable)
    if reverse:
        seq.reverse()        # preserve stability
    if key is not None:
        seq = [(key(elem), i, elem) for i, elem in enumerate(seq)]
    seq.sort(cmp)
    if key is not None:
        seq = [elem for (key, i, elem) in seq]
    if reverse:
        seq.reverse()
    return seq


Try it against the tests in Lib/test/test_builtin.py.

The differences from your version:
* >= 2.4 rather than just > 2.4
* renamed the parameter to iterable
* handle the case where both cmp and key are defined
* add an enumerated tie breaker to prevent full key comparisons
* preserve by using reverse twice

The real sorted() does the same thing but is implemented a bit differently.  A
custom key wrapper is applied to each object so that only the key value gets
compared (no need for a full tuple with a tie breaker value).

Raymond Hettinger






More information about the Python-list mailing list