Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: determining whether any item in sequence is equal to any other

I'd like to compare multiple objects and return True only if all objects are not equal among themselves. I tried using the code below, but it doesn't work. If obj1 and obj3 are equal and obj2 and obj3 are not equal, the result is True.

obj1 != obj2 != obj3

I have more than 3 objects to compare. Using the code below is out of question:

all([obj1 != obj2, obj1 != obj3, obj2 != obj3])
like image 666
msampaio Avatar asked Jul 30 '12 19:07

msampaio


2 Answers

@Michael Hoffman's answer is good if the objects are all hashable. If not, you can use itertools.combinations:

>>> all(a != b for a, b in itertools.combinations(['a', 'b', 'c', 'd', 'a'], 2))
False
>>> all(a != b for a, b in itertools.combinations(['a', 'b', 'c', 'd'], 2))
True
like image 194
BrenBarn Avatar answered Oct 13 '22 18:10

BrenBarn


If the objects are all hashable, then you can see whether a frozenset of the sequence of objects has the same length as the sequence itself:

def all_different(objs):
    return len(frozenset(objs)) == len(objs)

Example:

>>> all_different([3, 4, 5])
True
>>> all_different([3, 4, 5, 3])
False
like image 18
Michael Hoffman Avatar answered Oct 13 '22 19:10

Michael Hoffman