Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python comparison for trees represented as tuples

I'm representing trees with tuples. Say

t1=(t2,t3) and t4=(t5,t6)  

Is it true that when comparing two such trees with ==, it first tests if references t2 and t5 are equal then if references t3 and t6 are equal, if they are not equal then it tries to compare the actual contents of t2 and t5, then the contents of t3 and t6 ?
LE: The following code doesn't call __eq__ it seems that my assumption is right, and that it doesn't evaluate the tuples recursively as I understand from the documentation.

class C:
  def __init__(self,a):
    self.a=a
  def __eq__(self,oth):
    print self.a,oth.a
    return oth.a==self.a

p=(C(1),C(2))
l=(p,p)
f=(p,p)
print l==f 

On the other hand this code does call __eq__

   q=(C(1),C(2))
   p=(C(1),C(2))
   l=(q,q)
   f=(p,p)
   print l==f 
like image 392
titus Avatar asked Jul 23 '26 22:07

titus


2 Answers

Yes, tuples attempt to short-circuit the comparison process so two tuples are equal if they are the same tuple or if their elements are either identical or equal.

In particular:

>>> nan = float('NaN')
>>> left = (nan, nan)
>>> right = (nan, nan)
>>> left==right
True
>>> left[0]==right[0]
False

which seems pretty broken.

like image 139
Duncan Avatar answered Jul 26 '26 14:07

Duncan


From the documentation:

Sequence types also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.

Details about comparisons of the elements are also documented.

like image 42
Björn Pollex Avatar answered Jul 26 '26 13:07

Björn Pollex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!