strange behavior of the comparison operator

Grant Edwards grante at visi.com
Wed Aug 29 13:17:23 EDT 2001


In article <mailman.999103053.7875.python-list at python.org>, Ignacio Vazquez-Abrams wrote:
>On Wed, 29 Aug 2001, Nicolas Evrard wrote:
>
>> Hello everyone, this is my first post to the list and let me say that I
>> find python really exciting ... Looks a bit like scheme but is fast and
>> have a large community of users ...
>>
>> Here 's what I've done :
>>
>> To try the __comp__ method I've done a class for complex number (the usual
>> example). But here are the result I've got :
>>
>> >>> Complex(7,2).__comp__(Complex(3,4))
>> 1
>> >>> Complex(7,2) < Complex(3,4)
>> 1

How about adding some print statements to __comp__ to print out the values
of self.r, other.r, self.i, other.i?

>> the definition of __comp__ I've done :
>>
>>     def __comp__(self, other) :
>>         if self.r < other.r :
>>             return -1
>>         elif self.r == other.r :
>>             if self.i < other.i :
>>                 return -1
>>             elif self.i == other.i : return 0
>>         else : return 1
>>
>> But in the reference manual it says that __comp__ should return a positive
>> integer if self > other ... and obviously it isn't the case.
>
>Mmm. The question becomes "When do you consider one complex number to be
>greater or less than another?" Answer that question first and you will find
>your solution.

Uh, he has answered that question.  It may not be an answer you like, but
he's answered the question and written a __comp__ method to impliment it.

The only problem I see is that the case where self.r==other.r and self.i >
other.i isn't handled.  That wouldn't cause the problem you've observed, but
I'd do something like:
 
  def __comp__(self, other):
    if self.r < other.r:
       return -1
    elif self.r > other.r:
       return 1
    else:
       if self.i < other.i:
          return -1
       elif self.i > other.i:
          return 1
       else:
          return 0
	  
-- 
Grant Edwards                   grante             Yow!  The Korean War must
                                  at               have been fun.
                               visi.com            



More information about the Python-list mailing list