boolean xor

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


"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
>
> Bingo -- I *was* starting to think I should post about that.  For least-
> astonishment purposes, I'd thus like the xor function to behave similarly:
> return either A or B if at all possible (it may not be, of course, if
> both A and B are true).  E.g.,
>
> def xor(A,B):
>     if not A: return B
>     if not B: return A
>
Bzzzt. You need a "return 1" at the end of that. Look:

>>> def tf(x):
...  if x: return 1
...  else: return 0
...
>>> def xor(A, B):
...  if A: return B
...  if B: return A
...
>>> for A, B in (["", ""], ["", 't'], ['t', ''], ['t', 't']):
...  print tf(A), tf(B), tf(xor(A, B))
...
0 0 0   <<<< aarrrggghhh~~~!!!!
0 1 0
1 0 0
1 1 1

Better check my fix works: not often I get a chance to correct the
martellibot!

>>> def xor(A, B):
...  if A: return B
...  if B: return A
...  return 1
...
>>> 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.

regards
 Steve





More information about the Python-list mailing list