How do I create a function sublist()
that takes two lists, list1
and list2
, and returns True
if list1
is a s
Here's an iterative solution which should have optimal asymptotics:
def sublist(x, y):
if x and not y:
return False
i, lim = 0, len(y)
for e in x:
while e != y[i]:
i += 1
if i == lim:
return False
i += 1
return True
@sshashank124's solution has the same complexity, but the dynamics will be somewhat different: his version traverses the second argument multiple times, but because it pushes more work into the C layer it'll probably be much faster on smaller input.
Edit: @hetman's solution has essentially the same logic, but is much more Pythonic, although, contrary to my expectation, it seems to be slightly slower. (I was also incorrect about the performance of @sshashan124's solution; the overhead of the recursive calls appears to outweigh the benefit of doing more work in C.)