sorting list of complex numbers

Paul Rubin http
Tue Nov 18 11:41:58 CET 2008

skip at writes:
> but how do I then do a secondary sort by the imaginary part,...
> Is there a way to do this using just the key arg, no extra data structures?

Clever solutions involving multiple sorts aside, I think what they
really want you to do is something like (untested):

    class mkKey(complex):
       def __lt__(self, other):
           a = cmp(self.real, other.real)
           return a if a else cmp(self.imag, other.imag)



for fancier structures you'd need a full blown class implementation
with an init method.  Either way you end up temporarily allocating a
lot of extra structures, but at least they're not all in memory
simultaneously like in the DSU pattern.

More information about the Python-list mailing list