boolean xor

Steve Holden sholden at holdenweb.com
Thu Jan 11 08:03:07 EST 2001


"Andrew Dalke" <dalke at acm.org> wrote in message
news:93jls9$v12$1 at slb3.atl.mindspring.net...
> Rainer Deyke wrote:
> >If you want to play that way, the previous version is also flawed:
> >
> >not ( (a and b) or (not (a or b)) )
> >
> >In any case except where both 'a' and 'b' are true, the truth
> >value of 'a' is calculated twice.
>
> True, but I didn't really say that.  Here's a
> recapitulation of the thread.
>
> Aahz said he was using:
> def xor(a,b):
>     return not ( (a and b) or (not (a or b)) )
>
> Nicolas (ndev22 at yahoo.com) suggested instead using:
> def xor(a,b):
>   return not(a==b)
>
> I pointed out that Aahz's expression compares the truth value
> of the object and doesn't compare things them directly, so
> the proper form of Nicolas' code must use operator.truth.
>
> You applied DeMorgan's law to my quote of Aahz's original
> statement, to get:
> def xor(a, b):
>     return (a or b) and not (a and b)
>
> This was a backtrack on the thread and I was actually pointing
> out the difference between your modified form of Aahz's
> code and my corrected form of Nicolas's interpretation of
> Aahz's.
>
> Got it?  :)
>
>                     Andrew
>                     dalke at acm.org

A possibly salient point which hasn't been explicitly stated in this thread
(but might have been, seventeen days ago, my aging memory and general
decreptitude being what it is) is that the binary logical operators
short-circuit, and return the value of the last operand they evaluated. Even
more explicitly:

    A and B returns A (without evaluating B) if A evaluates to false:
    so you might get an empty list, a null string, whatever

    A or B returns B if A evaluates to false:
    so you might get *anything*

Because the == operator is pretty much a value comparison, it will not (for
example) accept that the empty list and the empty tuple are equal, even
though they are, for Boolean purposes, both false. So you need to compare
for equality of the Boolean values associated with things, rather than the
things themselves.

The "not" operator will always return 0 or 1, but "and" and "or" are only
guaranteed to return something which will yield the correct truth value in a
Boolean context.  So the only way to *guarantee* a truly Boolean result is
to ensure "not" is applied at the top level of your expression. I have even
used

    not not X

to map Boolean truth to (1, 0). But that's not something you wouldn't not
want to do on a regular basis, probably.

And, of course, perhaps nobody cared.  Sorry.

getting-tangled-in-his-own-knots-ly y'rs  - steve






More information about the Python-list mailing list