boolean xor
Alex Martelli
aleaxit at yahoo.com
Fri Jan 12 04:58:05 EST 2001
"Steve Holden" <sholden at holdenweb.com> wrote in message
news:61t76.2471$6i.33339 at e420r-atl2.usenetserver.com...
[snip]
> > 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:
*blink* -- do I?
> >>> def tf(x):
> ... if x: return 1
> ... else: return 0
> ...
> >>> def xor(A, B):
> ... if A: return B
> ... if B: return A
Sorry, what's this purported "xor"? It's "if not" in each
case, see my code you quote above.
> ...
> >>> 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!
I post enough actual imprecisions and outright errors without
taking some _good_ code I may occasionally happen to post as
such a 'chance'!-)
With my proposed definition of 'xor' (WITH the 'not's in it, as
originally posted):
>>> def xor(a,b):
... if not a: return b
... if not b: return a
...
>>> def tf(a):
... return not not a
...
>>> for a in ['', 'foo']:
... for b in ['', 'bar']:
... print tf(a), tf(b), tf(xor(a,b)), repr(xor(a,b))
...
0 0 0 ''
0 1 1 'bar'
1 0 1 'foo'
1 1 0 None
>>>
which seems to me to be exactly what I was talking about: my 'xor'
returns something with a truth value congruent with the exclusive
or's truth table (and, in that, it's absolutely nothing special);
but, specifically, it doesn't return "just any old true [false]
value" -- it returns either A or B if this is feasible, the only
exception being when both arguments are 'true', in which case it
can't return either of them (because it must give something with
a truthvalue of 'false'!) and therefore returns None.
Unlikely to be of any practical value, I guess (unlike Python's
and/or, which DO get significant added-value from always returning
one of their operands, IMHO) -- but I thought it was cute.
Alex
More information about the Python-list
mailing list