boolean xor

Steve Holden sholden at holdenweb.com
Thu Jan 11 21:13:10 EST 2001


"Steve Holden" <sholden at holdenweb.com> wrote in message
news:61t76.2471$6i.33339 at e420r-atl2.usenetserver.com...
> "Alex Martelli" <aleaxit at yahoo.com> wrote in message
> news:93kofr01bg2 at news1.newsguy.com...
> > "Steve Holden" <sholden at holdenweb.com> wrote in message
> > news:Tbi76.10504$X3.66627 at e420r-atl1.usenetserver.com...
> >     [snip]
> > > 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
> >
[ ... ]
> >>> for A, B in (["", ""], ["", 't'], ['t', ''], ['t', 't']):
> ...  print tf(A), tf(B), tf(xor(A, B))
> ...
> 0 0 1
> 0 1 0
> 1 0 0
> 1 1 1
>
> Yup, that appears to do it. Still, returning that "1" doesn't seem very
> Pythonic. Can;t think of anything else to do, however, since not (either
> argument) will give 1 anyway in that case.
>
Well, I warned you about the decrepitude.  What this returns, of course, is
precisely the logical converse of what it should.  The truth table we
actually want is:

0 0 0
0 1 1
1 0 1
1 1 0

This is good, though, because the implicit None return will give us what we
need in the final case. Here we go, with an added display of the real
values:

>>> def xor(A, B):
...  if not A: return B
...  if not B: return A
...
>>> for A, B in ([[], ()], [[], 't'], ['t', ()], ['t', 't']):
...  print tf(A), tf(B), tf(xor(A, B)), A, B, xor(A, B)
...
0 0 0 [] () ()
0 1 1 [] t t
1 0 1 t () t
1 1 0 t t None

This seems a little more Pythonic, and has the added advantage of producing
a logically correct result. Can we go further?

helps-if-you-don't-assume-martellibot-infallibility-but-it's-a-good-bet-ly
y'rs  - steve





More information about the Python-list mailing list