Skip to content

Instantly share code, notes, and snippets.

@fluency03
Created November 21, 2016 14:28
Show Gist options
  • Select an option

  • Save fluency03/15eb51e41d5a25353ffa45e0402f4e28 to your computer and use it in GitHub Desktop.

Select an option

Save fluency03/15eb51e41d5a25353ffa45e0402f4e28 to your computer and use it in GitHub Desktop.
def seq_in_seq(subseq, seq):
"""Return an index of `subseq`uence in the `seq`uence.
Or `-1` if `subseq` is not a subsequence of the `seq`.
The time complexity of the algorithm is O(n*m), where
n, m = len(seq), len(subseq)
>>> index([1,2], range(5))
1
>>> index(range(1, 6), range(5))
-1
>>> index(range(5), range(5))
0
>>> index([1,2], [0, 1, 0, 1, 2])
3
Args:
subseq (list):
seq (list):
Returns:
int: position of subseq on seq.
"""
i, n, m = -1, len(seq), len(subseq)
if m == 0:
return -1
try:
while True:
i = seq.index(subseq[0], i + 1, n - m + 1)
if subseq == seq[i:i + m]:
return i
except ValueError:
return -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment