Reputation: 8647
I want the results of the function to be:
This is my try at it:
>>> def consistent(x):
... x_filtered = filter(None, x)
... return len(x_filtered) in (0, len(x))
...
>>> consistent((0,1))
False
>>> consistent((1,1))
True
>>> consistent((0,0))
True
[Bonus]
What should this function be named?
Upvotes: 13
Views: 5224
Reputation: 331
Just yet another way of doing it, given list l:
sum([int(bool(x)) for x in l]) in (0, len(l))
>>> a=['',None,0,False]
>>> b=[1,True,'ddd']
>>> c=[0,1,False,True,None]
>>> for l in (a,b,c):
... print sum([int(bool(x)) for x in l]) in (0, len(l))
...
True
True
False
Upvotes: 0
Reputation: 3229
Not so brief, but shortcuts without messing around with 'tee' or anything like that.
def unanimous(s):
s = iter(s)
if s.next():
return all(s)
else:
return not any(s)
Upvotes: 0
Reputation:
def all_equals(xs):
x0 = next(iter(xs), False)
return all(bool(x) == bool(x0) for x in xs)
Upvotes: 2
Reputation: 63709
Piggybacking on Ignacio Vasquez-Abram's method, but will stop after first mismatch:
def unanimous(s):
it1, it2 = itertools.tee(iter(s))
it1.next()
return not any(bool(a)^bool(b) for a,b in itertools.izip(it1,it2))
While using not reduce(operators.xor, s)
would be simpler, it does no short-circuiting.
Upvotes: 3
Reputation: 798576
def unanimous(it):
it1, it2 = itertools.tee(it)
return all(it1) or not any(it2)
Upvotes: 24
Reputation: 21918
def all_bools_equal(lst):
return all(lst) or not any(lst)
See: http://docs.python.org/library/functions.html#all
See: http://docs.python.org/library/functions.html#any
Upvotes: 11