Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordered subsets test

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.

like image 900
msampaio Avatar asked Aug 05 '12 22:08

msampaio


1 Answers

You can simply use an iterator to keep track of the position in B

>>> A = (0, 1, 2)
>>> B = (0, 3, 1, 4, 2)
>>> b_iter = iter(B)
>>> all(a in b_iter for a in A)
True
like image 84
John La Rooy Avatar answered Nov 08 '22 16:11

John La Rooy