sorting a list and counting interchanges

Raymond Hettinger vze4rx4y at verizon.net
Wed Apr 6 20:35:30 EDT 2005


[RickMuller]
> I have to sort a list, but in addition to the sorting, I need to
> compute a phase factor that is +1 if there is an even number of
> interchanges in the sort, and -1 if there is an odd number of
> interchanges.

This sounds like a homework problem but will offer a solution anyway:

>>> phase = 1
>>> def mycmp(x, y):
        global phase
        phase = -phase
        return cmp(x, y)

>>> sorted('abracadabra', cmp=mycmp)
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
>>> phase
-1



Raymond Hettinger





More information about the Python-list mailing list