Comparison of functions

Steven Bethard steven.bethard at gmail.com
Mon Aug 1 13:47:46 EDT 2005


Steven D'Aprano wrote:
> You are confusing mathematical ordering with sorting a list. Here, I will
> sort some mixed complex and real numbers for you. If you look at them
> closely, you will even be able to work out the algorithm I used to sort
> them.
> 
> 1
> 1+0j
> 1+7j
> 2
> 2+3j
> 3+3j
> 3-3j
> 3+4j
> 4
> 4+2j

It's clear which algorithm you used to sort these:

py> lst = [3+3j, 3+4j, 1+7j, 2, 3-3j, 4, 4+2j, 1, 1+0j, 2+3j]
py> def complex2tuple(c):
... 	c = complex(c)
... 	return c.real, c.imag
...
py> for item in sorted(lst, key=complex2tuple):
...     print item
...
1
(1+0j)
(1+7j)
2
(2+3j)
(3-3j)
(3+3j)
(3+4j)
4
(4+2j)

What isn't clear is that this should be the default algorithm for 
sorting complex numbers.

STeVe



More information about the Python-list mailing list