missing 'xor' Boolean operator

Dr. Phillip M. Feldman pfeldman at verizon.net
Wed Jul 15 00:07:14 EDT 2009

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), and should return True if and only
if the number of input arguments that evaluate to True is odd (see
www.mathworld.com article on xor).  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

   result= False

   for arg in args:
      if bool(arg): result= not result

   return result

MRAB-2 wrote:
> Ethan Furman wrote:
>> Robert Kern wrote:
>>> On 2009-07-14 14:56, Dr. Phillip M. Feldman wrote:
>>>> != does do what I want, except that it doesn't indicate to someone 
>>>> reading
>>>> the code that the operands are being treated as logicals.  
>>>> (Readability is
>>>> supposed to be one of the major selling points of Python).  But, this
>>>> is
>>>> probably good enough.
>>> In the words of those greater than myself, "Not every one-liner needs 
>>> to be in the standard library."
>>> def xor(a, b):
>>>     return bool(a) != bool(b)
>> Let's see...
>>   and returns the last object that is "true"
>>   or  returns the first object that is "true"
>> so should xor return the only object that is "true", else False/None?
>> def xor(a, b)
>>     if a and b:
>>         return None
>>     elif a:
>>         return a
>>     elif b:
>>         return b
>>     else:
>>         return None
> How about:
> def xor(a, b):
>      return not b and a or not a and b
> -- 
> http://mail.python.org/mailman/listinfo/python-list

View this message in context: http://www.nabble.com/missing-%27xor%27-Boolean-operator-tp24485116p24491580.html
Sent from the Python - python-list mailing list archive at Nabble.com.

More information about the Python-list mailing list