Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an ordered non-consecutive subsequence is in array? Python

I'd be surprised if this hasn't been asked yet.

Let's say I have an array [5,6,7,29,34] and I want to check if the sequence 5,6,7 appears in it (which it does). Order does matter.

How would I do this?

like image 788
Graviton Avatar asked Mar 06 '26 13:03

Graviton


1 Answers

Just for fun, here is a quick (very quick) and dirty (very dirty) solution (that is somewhat flawed, so don't really use this):

>>> str([5,6,7]).strip('[]') in str([5,6,7,29,34])
True

The RightWay™ is likely to use list.index() to find candidate matches for the first element and then verify the full match with slicing and list equality:

>>> def issubsequence(sub, seq):
        i = -1
        while True:
            try:
                i = seq.index(sub[0], i+1)  # locate first character
            except ValueError:
                return False
            if seq[i : i+len(sub)] == sub:  # verify full match
                return True         

>>> issubsequence([5, 6, 7], [5,6,7,29,34])
True
>>> issubsequence([5, 20, 7], [5,6,7,29,34])
False

Edit: The OP clarified in a comment that the subsequence must be in order but need not be in consecutive positions. That has a different and much more complicated solution which was already answered here: How do you check if one array is a subsequence of another?

like image 121
Raymond Hettinger Avatar answered Mar 09 '26 03:03

Raymond Hettinger



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!