missing 'xor' Boolean operator
Miles Kaufmann
milesck at umich.edu
Wed Jul 15 07:08:42 CEST 2009
On Jul 15, 2009, at 12:07 AM, Dr. Phillip M. Feldman wrote:
> I appreciate the effort that people have made, but I'm not impressed
> with any
> of the answers. For one thing, xor should be able to accept an
> arbitrary
> number of input arguments (not just two)
You originally proposed this in the context of the existing short-
circuit boolean operators. Those operators (being infix) take only
two operands.
> and should return True if and only
> if the number of input arguments that evaluate to True is odd
The existing and/or operators always return the value of one of the
operands--not necessarily True or False--which is another important
property, but one that can't be translated fully to xor. Given the
lack of context in your original post, hopefully you'll forgive me
being unimpressed by your not being impressed. :)
> Here's my code:
>
> def xor(*args):
> """xor accepts an arbitrary number of input arguments, returning
> True
> if and only if bool() evaluates to True for an odd number of the
> input
> arguments."""
>
> result= False
>
> for arg in args:
> if bool(arg): result= not result
>
> return result
If all you want is a True or False result, I'd write it like this:
import operator
def xor(*args):
return reduce(operator.xor, map(bool, args)) # or imap
In order to make it act more like the other logical operators, I'd use
MRAB's 2-argument xor as the reducer--though I can't really see the
utility.
def xor2(a, b):
return (not b and a) or (not a and b)
def xor(*args):
return reduce(xor2, args)
You may also find this question interesting:
http://stackoverflow.com/questions/432842/
-Miles
More information about the Python-list
mailing list