Belmin Fernandez
Belmin Fernandez

Reputation: 8647

Pythonic way to check if: all elements evaluate to False -OR- all elements evaluate to True

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

Answers (7)

Alex Atho
Alex Atho

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

greggo
greggo

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

user97370
user97370

Reputation:

def all_equals(xs):
    x0 = next(iter(xs), False)
    return all(bool(x) == bool(x0) for x in xs)

Upvotes: 2

PaulMcG
PaulMcG

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

Kabie
Kabie

Reputation: 10673

def AllTheSame(iterable):
    return any(iterable) is all(iterable)

Upvotes: -1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798576

def unanimous(it):
  it1, it2 = itertools.tee(it)
  return all(it1) or not any(it2)

Upvotes: 24

dkamins
dkamins

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

Related Questions