Basically lets say i have:
>>> a = [1,3,2,2,2]
>>> b = [1,3,2]
I want to see if the all the elements in b, exists within a, and in the same order. So for the above example b would exist within a.
I am kinda hoping theres a really simple one line answer.
This is a simple O(n * m) algorithm:
any(a[i:i + len(b)] == b for i in range(len(a) - len(b) + 1))
Note that is not the fastest way of doing this. If you need high performance you could use similar techniques to those used in string searching algorithms.
If by 'in the same order' you meant subsequence (as opposed to substring) then this non-one-liner should work fast:
def is_subsequence(x, y):
i, j = 0, 0
while i < len(x) and j < len(y):
if x[i] == y[j]:
i += 1
j += 1
return i == len(x)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With