tags:

views:

193

answers:

4

Is there a fast way to check if one set entirely contains another?

Something like:

>>>[1, 2, 3].containsAll([2, 1])
True

>>>[1, 2, 3].containsAll([3, 5, 9])
False
A: 

WRONG-ANSWER

This is an order comparison, not a set content comparison:

>>> [1,2,3] > [1,2]
True
>>> [1,2,3] > [3,5,9]
False
>>> 

As the above answer states, convert to a set first, then use set methods.

Warren P
That doesn't actually do a subset check, just an element-by-element order comparison. The fact that it gives the right answer in those two cases is mere accident.
Thomas Wouters
but [1,2,3] > [1,2,3] => False, it is just comparison, not contains operation
dragoon
It was a fun accident.
Warren P
This is my most downvoted answer.
Warren P
+15  A: 

Those are lists, but if you really mean sets you can use the issubset method.

>>> s = set([1,2,3])
>>> t = set([1,2])
>>> t.issubset(s)
True
>>> s.issuperset(t)
True

For a list, you will not be able to do better than checking each element.

danben
+4  A: 

Try issubset:

>>> a=set([1,2,3])
>>> b=set([1,2])
>>> b.issubset(a)
True
>>> a.issubset(b)
False
wump
+1  A: 

For completeness: this is equivalent to issubset (although arguably a bit less explicit/readable):

>>> set([1,2,3]) >= set([2,1])
True
>>> set([1,2,3]) >= set([3,5,9])
False
ChristopheD