amphibient - 1 year ago 96

Python Question

What would be the most minimal way of determining whether only one element in a boolean list is

`True`

`Python`

I was thinking of converting each boolean to 0 (false) or 1 (true) and adding them all up and checking if the sum is 1. That is pretty minimalist but I was wondering if there is a (bitwise) operation that will return true if only one element is true and all the other ones false, which would save me the bool-->int conversion (however simple it is). I am mostly just curious on whether such a bitwise operation exists.

Answer Source

Python `bool`

subclass from `int`

so you don't need to do any conversion:

```
>>> sum([True, False, False])
1
>>> sum([True, True, True])
3
```

This solution doesn't short-circuit however ... there are some cases where you might want to be able to bail out earlier:

```
result = 0
for item in boolean_iterable:
result += item
if result > 1:
break # Short-circuit early
```

However, unless your boolean iterables are really large, and you expect to short-circuit frequently, I would expect this to perform worse than the `sum`

in the average case (which can push the loop to more optimized code).

Also if you're looking for clever ways to do this with bitwise arithmetic, you can use `xor`

in a `reduce`

operation:

```
>>> from functools import reduce
>>> import operator
>>> reduce(operator.xor, [True, False, False], False)
True
>>> reduce(operator.xor, [True, False, True], False)
False
>>> reduce(operator.xor, [], False)
False
>>> reduce(operator.xor, [True], False)
True
```

But I wouldn't advise using this version :-)