Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need at python script that will complete the task asked below, thanks for your

ID: 673474 • Letter: I

Question

I need at python script that will complete the task asked below, thanks for your time and help

Let list1 and list2 be two lists of integers. We say that list1 is a sublist of list2 if the elements in list1 appear in list2 in the same order as they appear in list1, but not necessarily consecutively. For example, if list1 is defined as

[15, 1, 100]

and list2 is defined as [20, 15, 30, 50, 1, 100]

then list1 is a sublist of list2 because the numbers in list1 (15, 1, and 100) appear in list2 in the same order. However, list [15, 50, 20]

is not a sublist of list2. Implement function sublist() that takes as input lists list1 and list2 and returns

True if list1 is a sublist of list2, and False otherwise.

>>> sublist([15, 1, 100], [20, 15, 30, 50, 1, 100])

True

>>> sublist([15, 50, 20], [20, 15, 30, 50, 1, 100])

False

Explanation / Answer

1st Way :

Explaination : Basically it goes through each element of the sublist, and sees if it can find that same element in the part of the complete list it hasn't looked at yet. If it makes it through the entire sublist it means we have a match [hence the else statement on the for loop]. If we run out of elements to look at in the complete list, it means we don't have a match.

This is one way to do it in linear time and constant space with an iterator:

def sublist(a, b):
seq = iter(b)
try:
for x in a:
while next(seq) != x: pass
else:
return True
except StopIteration:
pass
return False

Further Explainations :
If you need to micro-optimize this, I suspect itertools.dropwhile(x.__ne__, seq) might be faster than an explicit loop (because it iterates in C), or a for loop with a break (because it iterates with fewer bytecodes) might be faster than a while loop around next, especially in CPython 2.x. I

2nd Way :
Will not work if duplicates allowed :

def sublist(a,b):
try:
return a[0] in b and sublist(a[1:],b[1+b.index(a[0]):])
except IndexError:
return True

>>> sublist([15, 1, 100], [20, 15, 30, 50, 1, 100])
True
>>> sublist([15, 50, 20], [20, 15, 30, 50, 1, 100])
False

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote