missing 'xor' Boolean operator
Mark Dickinson
dickinsm at gmail.com
Wed Jul 15 03:44:48 EDT 2009
On Jul 15, 5:07 am, "Dr. Phillip M. Feldman" <pfeld... at verizon.net>
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), and should return True if and only
> if the number of input arguments that evaluate to True is odd.
Well, that's not exactly what you originally asked for. But it's
still a one-liner:
def xor(*args): return bool(sum(map(bool, args)) % 2)
or perhaps
def xor(*args): return bool(len(filter(None, args)) & 1)
> 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
It's more idiomatic to say "if arg: ..." rather than "if bool
(arg): ...".
>
> return result
Mark
More information about the Python-list
mailing list