boolean xor
Tim Hochberg
tim.hochberg at ieee.org
Thu Jan 11 21:06:54 EST 2001
"Steve Holden" <sholden at holdenweb.com> wrote in message
> "Alex Martelli" <aleaxit at yahoo.com> wrote in message
> news:93kofr01bg2 at news1.newsguy.com...
[SNIP]
> > 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
[SNIP]
> Better check my fix works: not often I get a chance to correct the
> martellibot!
I suspect that head thwacking will soon commence
> >>> 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.
Uhm, unless I slipped into an alternate universe at some point since they
were cramming this stuff into my brain, the truth table for xor is:
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
The rest I leave as an excercise for the reader.
-tim
More information about the Python-list
mailing list