Incomparable abominations

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Mon Mar 24 18:50:48 EST 2003


> From: Niki Spahiev [mailto:spahievi at vega.bg]
> 
> PM> Niki Spahiev <spahievi at vega.bg> writes:
> >>
> >> I do. It's easiest way to get point on the convex hull of 
> point set. 
> >> (point === complex).
> 
> PM> Why not point === tuple of 2 co-ordinates? What do complex numbers
> PM> gain you (given that they don't give you sorting properties...)
> 
> Because points have vector properties e.g. middle = (a+b)/2 works for
> complex numbers.

One thing I thought of ... try subclassing complex and overriding __lt__, etc.

Of course, then you lose direct syntactical support, but it's pretty damned easy to convert a complex to your Point class at that stage ...

import traceback

class ComplexPoint (complex):

    def __lt__(self, other):
        return (self.real, self.imag,) < (other.real, other.imag,)

    def __gt__(self, other):
        return (self.real, self.imag,) > (other.real, other.imag,)

    def __le__(self, other):
        return (self == other) or (self < other)

    def __ge__(self, other):
        return (self == other) or (self > other)

a = [1+0j, 3+0j, 2+0j, 1+0j, 1+1j, 2+1j]
print a

try:
    a.sort()
except:
    print
    traceback.print_exc()

a = map(ComplexPoint, a)
a.sort()

print
print a

a = ComplexPoint(1)
b = ComplexPoint(2)

print
print a == b
print a != b
print a < b
print a <= b
print a >= b
print a > b

Python 2.2 ...
---------- Run ----------
[(1+0j), (3+0j), (2+0j), (1+0j), (1+1j), (2+1j)]

Traceback (most recent call last):
  File "C:\python\modules\complexpoint.py", line 21, in ?
    a.sort()
TypeError: cannot compare complex numbers using <, <=, >, >=

[(1+0j), (1+0j), (1+1j), (2+0j), (2+1j), (3+0j)]

0
1
1
1
0
0

Tim Delaney





More information about the Python-list mailing list