missing 'xor' Boolean operator
Anthony Tolle
anthony.tolle at gmail.com
Thu Jul 16 09:23:57 EDT 2009
On Jul 15, 8:32 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> Among other things, that uses quadratic time! Why do you want to keep
> popping items from that list instead of iterating through it anyway?
>
> Anyway, I think you wrote something close to this:
> ...
Very true! I didn't think about the problems with pop(). I was using
it as a shortcut for pulling off the first operand. I forgot that if
you start with an initial operand of "False", the result will be the
same (0 xor X = X)
While I'm not sure how useful it would be, here's a version of the
first function that returns one of the operands (ala AND and OR),
except in the case where there is an even number of True elements,
where it returns False:
def xor(*operands):
r, rprime = False, False
for x in operands:
xprime = bool(x)
if rprime:
if xprime:
r, rprime = False, False
else:
r, rprime = x, xprime
return r
>>> xor(0, 0)
0
>>> xor(0, 1)
1
>>> xor(1, 0)
1
>>> xor(1, 1)
False
>>> xor(0, 1, 2)
False
>>> xor(0, 1, 2, 3)
3
>>> xor(None, [])
[]
More information about the Python-list
mailing list