It uses a linear time approach (in the longest set), which does not require any hashing. It exploits the fact that since both sets are ordered, earlier elements in the set do not need to be re-checked:
>>> def subset_test(a, b): ... b = iter(b) ... try: ... for i in a: ... j = b.next() ... while j != i: ... j = b.next() ... except StopIteration: ... return False ... return True ...
A few tests:
>>> subset_test((0, 1, 2), (0, 3, 1, 4, 2)) True >>> subset_test((0, 2, 1), (0, 3, 1, 4, 2)) False >>> subset_test((0, 1, 5), (0, 3, 1, 4, 2)) False >>> subset_test((0, 1, 4), (0, 3, 1, 4, 2)) True
I am sure this is correct - let me know if you see any problems.
source share