boolean xor

Andrew Dalke dalke at acm.org
Wed Jan 10 13:26:50 EST 2001


ndev42 at yahoo.com wrote:
>A boolean xor is a detector of differences. Knowing that, you can
>simply write:
>
>def xor(a,b):
> return not(a==b)

The expression "not ( (a and b) or (not (a or b)) )"
checks the truth value of a and b, which means it calls
__nonzero__ or __len__ as unary methods of the object.
The == is a binary operator which may call the __coerce,
__cmp__ or __rcmp__ methods, so your version does something
different than the original code.

For your form to work, what you need to do instead is

  return not (operator.truth(a) == operator.truth(b))

Another thing to think about:

>>> def xor(a,b): return not(a == b)
...
>>> xor(4,5)
1
>>> def xor(a,b): return not ( (a and b) or (not (a or b)) )
...
>>> xor(4,5)
0
>>> def xor(a,b): return not (operator.truth(a) == operator.truth(b))
...
>>> xor(4,5)
0
>>>

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list