Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a list is a subsequence of another list in order [duplicate]

Tags:

python

list

I have a list input:

[1, 2, 4, 3, 5, 7, 5, 3, 8, 3, 8, 5, 8, 5, 9, 5, 7, 5, 7, 4, 9, 7, 5, 7, 4, 7, 4, 7, 8, 9, 7, 5, 7, 5, 4, 9, 3, 4, 8, 4, 8, 5, 3, 5, 4, 7, 3, 7, 3, 1, 2, 7, 1, 7, 2, 1]

I need to check if the elements of a lookup_list [1,2,3,4,5,7,8,9,5,4,3,2,1] are present in the above list in a spread out manner in the same sequence.

This will illustrate what I am trying to say:

[1, 2, 4, 3, 5, 7, 5, 3, 8, 3, 8, 5, 8, 5, 9, 5, 7, 5, 7, 4, 9, 7, 5, 7, 4, 7, 4, 7, 8, 9, 7, 5, 7, 5, 4, 9, 3, 4, 8, 4, 8, 5, 3, 5, 4, 7, 3, 7, 3, 1, 2, 7, 1, 7, 2, 1]

The numbers in bold are the numbers from the lookup_list present in the same order in the input list, but with other irrelevant items in between as well.

Is there any way I can check for this?

This is the method I tried:

count = 0
a = 0
indices = []
for item in list:
    idx = -1
    if count < len(input_list):
        idx = list.index(input_list[count])
        if idx != -1:
            a = a +len(list[:idx])
            list = list[idx:]
            indices.append(a + idx)
    count = count +1
print(indices)

but it gave me the following result:

[0, 2, 5, 35, 25, 24, 33, 30, 33, 37, 38, 64, 54]

The issue is, the order of the lookup_list is not maintained in this method.

like image 641
user150599 Avatar asked Dec 14 '25 14:12

user150599


1 Answers

You could use an iterator over your input list. Call next to get each value. If you exhaust the iterator without finding all the matches, you will get a StopIteration and then you would return False.

def check(input_, lookup_list):
    it = iter(input_)
    try:
        for i in lookup_list:
            # read values from the input list until we find one which 
            # matches the current value from the lookup list
            while next(it) != i: 
                pass
        # we found matches for everything on the lookup list
        return True
    except StopIteration:
        # we tried to go past the end of the input list
        return False
like image 99
alani Avatar answered Dec 16 '25 04:12

alani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!