Christian Heimes wrote:
Chris Rebert wrote:
Using the xor bitwise operator is also an option:
bool(x) ^ bool(y)
I prefer something like:
bool(a) + bool(b) == 1
It works even for multiple tests (super xor):
if bool(a) + bool(b) + bool(c) + bool(d) != 1:
raise ValueError("Exactly one of a, b, c and d must be true")
Christian
super_xor! I like it!
In [23]: def super_xor(args, failure=False):
....: found_one = False
....: for item in args:
....: if item:
....: if found_one:
....: return failure
....: else:
....: found_one = item
....: return found_one or failure
In [25]: super_xor((0, 1, 0, []))
Out[25]: 1
In [26]: super_xor((0, 1, 0, [],('this',)))
Out[26]: False
In [27]: super_xor((0, {}, 0, [],()))
Out[27]: False
In [16]: def super_or(args, failure=False):
....: for item in args:
....: if item:
....: return item
....: else:
....: return failure
....:
In [17]: super_or((None, [], 0, 3, {}))
Out[17]: 3
In [18]: super_or((None, [], 0, (), {}))
Out[18]: False
In [19]: def super_and(args, failure=False):
....: for item in args:
....: if not item:
....: return failure
....: else:
....: return item
....:
In [20]: super_and((1, 2, 3))
Out[20]: 3
In [21]: super_and((1, 2, 3, 4))
Out[21]: 4
In [22]: super_and((1, 0, 3, 4))
Out[22]: False
A whole family of supers. :)
~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list