I want to test if an ordered set is a subset of a bigger ordered set. I used tuples and itertools.combinations
:
def subset_test(a, b):
return a in itertools.combinations(b, len(a))
For instance,
>>> subset_test((0, 1, 2), (0, 3, 1, 4, 2))
True
>>> subset_test((0, 1, 2), (0, 3, 2, 4, 1))
False
It works, but is slow when I test big tuples.
Simple way of doing this
For greater efficiency use
itertools
Here's a linear time approach (in the longest set) that doesn't require any hashing. It takes advantage of the fact that, since both sets are ordered, earlier items in the set don't need to be re-checked:
A few tests:
I'm pretty sure this is right -- let me know if you see any problems.
This should get you started
If the list comprehension throws a
KeyError
, then obviously the answer is alsoFalse
You can simply use an iterator to keep track of the position in B
What about this?
In this example a and b have ordered and unique elements and it checks if a is subset of b. Is this you want?
EDIT:
According to @Marcos da Silva Sampaio: "I want to test if A is a subset of the ordered set B."
It wouldn't be the case of:
In this case the order of a doesn't matters.
This should be pretty quick, but I have a faster one in mind I hope to have down soon:
Update: here's the faster one I promised.