So the problem of verifying if a list is a subsequence of another came up in a discussion, and I wrote code that seems to work (I haven't rigorously tested it).
IsSubequence.py
def is_subsequence(lst1, lst2):
"""
* Finds if a list is a subsequence of another.
* Params:
* `lst1` (`list`): The candidate subsequence.
* `lst2` (`list`): The parent list.
* Return:
* (`bool`): A boolean variable indicating whether `lst1` is a subsequence of `lst2`.
"""
l1, l2 = len(lst1), len(lst2)
if l1 > l2: #`l1` must be <= `l2` for `lst1` to be a subsequence of `lst2`.
return False
i = j = 0
d1, d2 = l1, l2
while i < l1 and j < l2:
while lst1[i] != lst2[j]:
j += 1
d2 -= 1
if d1 > d2: #At this point, `lst1` cannot a subsequence of `lst2`.
return False
i, j, d1, d2 = i+1, j+1, d1-1, d2-1
if d1 > d2:
return False
return True
I'm primarily concerned about performance.
[1,1]
a subsequence of[1,0,1]
? According to your code, it is. If you only want to consider continuous subsequences (eg.[1,1]
is not a subsequence of[1,0,1]
), you can use a string matching algorithm. The items of the two lists can be viewed as characters of two strings. \$\endgroup\$[1, 1]
is supposed to be a subsequence of[1, 0, 1]
. \$\endgroup\$