Ответ 1
def unanimous(it):
it1, it2 = itertools.tee(it)
return all(it1) or not any(it2)
Я хочу, чтобы результаты функции были:
Это моя попытка:
>>> 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]
Какую функцию следует называть этой функцией?
def unanimous(it):
it1, it2 = itertools.tee(it)
return all(it1) or not any(it2)
def all_bools_equal(lst):
return all(lst) or not any(lst)
Piggybacking по методу Игнасио Васкеса-Абрама, но остановится после первого несоответствия:
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))
При использовании not reduce(operators.xor, s)
будет проще, он не закорачивает.
def all_equals(xs):
x0 = next(iter(xs), False)
return all(bool(x) == bool(x0) for x in xs)
Не так краток, но ярлыки, не вмешивающиеся в "тройник" или что-то в этом роде.
def unanimous(s):
s = iter(s)
if s.next():
return all(s)
else:
return not any(s)
def AllTheSame(iterable):
return any(iterable) is all(iterable)