Skip to content

Instantly share code, notes, and snippets.

@paulocheque
Created July 8, 2017 18:30
Show Gist options
  • Save paulocheque/d3222ab37959f711f454a15048177dc8 to your computer and use it in GitHub Desktop.
Save paulocheque/d3222ab37959f711f454a15048177dc8 to your computer and use it in GitHub Desktop.
Find a seq in a list
def find_seq(seq, alist):
'''
Find the sequence @seq in the list @alist.
@seq: a list or tuple with size `m`.
@alist: a list or tuple with size `n`.
@return: True if @alist contains @seq, False otherwise.
Complexity: `O((n-m) * m) = O(n * m)`
'''
for index, item in enumerate(alist): # O(n)
sublist = alist[index:index+len(seq)]
if len(sublist) < len(seq):
break
if seq == sublist: # O(m)
return True
return False
# Tests
assert find_seq([], [1, 3, 4]) == True
assert find_seq([4], [1, 3, 4]) == True
assert find_seq([6, 7], [1, 3, 4, 5, 6, 7]) == True
assert find_seq([1, 3, 4], [1, 3, 4]) == True
assert find_seq([1, 3, 4], [1, 3, 4, 5]) == True
assert find_seq([1, 3, 4], [0, 1, 3, 4]) == True
assert find_seq([1, 3, 4], [5, 1, 3, 4, 6]) == True
assert find_seq([1, 2, 3, 4], [1, 2, 3, 5, 1, 2, 3, 6, 1, 2, 3, 7, 1, 2, 3, 4]) == True
assert find_seq([1, 3, 4], []) == False
assert find_seq([1, 3, 4], [1, 3]) == False
assert find_seq([1, 3, 4], [1, 3, 5]) == False
assert find_seq([1, 3, 4], [5, 1, 3, 6, 4]) == False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment