Comparison of functions

Dan Bishop danb_83 at yahoo.com
Mon Aug 1 01:01:10 EDT 2005


Steven D'Aprano wrote:
> On Sat, 30 Jul 2005 16:43:00 +0000, Adriano Varoli Piazza wrote:
>
> > If you want to treat numbers as strings, why not convert them before
> > sorting them?
>
> Because that changes the object and throws away information.

I think he meant doing something like

->>> lst = ['2+2j', 1+1j]
->>> lst.sort(key=str)
->>> lst
[(1+1j), '2+2j']

> > Python is just saying "He's trying to sort complex
> > numbers. No can do".
>
> Python is quite happy to sort a list with one single complex number and
> nothing else, so it is not SORTING complex numbers that Python objects
> to, merely greater or less than comparisons. It is an accident of
> implementation that Python blindly uses GT or LT comparisons for sorting
> complex numbers, but not other objects.

Python uses GT/LT comparisons for sorting *everything*.  The wart is
not in list.sort, but in the inconsistent implementation of the
comparison operators.

> ...
> Which has been my point all along: Python confuses the specific case of
> NUMERIC COMPARISONS with the general case of SORTING. Worse, Python
> doesn't even do that consistently: it is quite happy to let you compare
> floats with strings, even though mathematically that is just as
> much nonsense as to compare floats with complex numbers.
>
> As I've said, the two are similar enough that such a mistake is easy to
> make. And at this time, I'm not sure how to implement a better solution,
> or even if there is a better solution, but I am giving it some thought.

How's this?


# This would be the default cmp function for list.sort
def sortcmp(x, y):
   try:
      return x.__sortcmp__(y)
   except (AttributeError, TypeError):
      try:
         return -(y.__sortcmp__(x))
      except (AttributeError, TypeError):
         return cmp(x, y)

# Example class for __sortcmp__ method
class SaneComplex(complex):
   def __sortcmp__(self, other):
      other = complex(other)
      return cmp((self.real, self.imag), (other.real, other.imag))

lst = map(SaneComplex, [1, 1+0j, 1+7j, 2, 2+3j, 3+3j, 3-3j, 3+4j, 4,
4+2j])
lst.sort(sortcmp)
print lst




More information about the Python-list mailing list