In python, I have a list that should have one and only one truthy value (that is, bool(value) is True
). Is there a clever way to check for this
import collections
def only_n(l, testval=True, n=1):
counts = collections.Counter(l)
return counts[testval] == n
Linear time. Uses the built-in Counter class, which is what you should be using to check counts.
Re-reading your question, it looks like you actually want to check that there is only one truthy value, rather than one True
value. Try this:
import collections
def only_n(l, testval=True, coerce=bool, n=1):
counts = collections.Counter((coerce(x) for x in l))
return counts[testval] == n
While you can get better best case performance, nothing has better worst-case performance. This is also short and easy to read.
Here's a version optimised for best-case performance:
import collections
import itertools
def only_n(l, testval=True, coerce=bool, n=1):
counts = collections.Counter()
def iterate_and_count():
for x in itertools.imap(coerce,l):
yield x
if x == testval and counts[testval] > n:
break
counts.update(iterate_and_count())
return counts[testval] == n
The worst case performance has a high k
(as in O(kn+c)
), but it is completely general.
Here's an ideone to experiment with performance: http://ideone.com/ZRrv2m