In: Computer Science
I am working on exercise 5.48 from Introduction to Computing using python (Author: Perkovic).
Problem Question: 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 list 2 in the same order as they appear in list1, but not necessarily consecutively. For ex, if list1 is defined as [15,1,100] and list2 is defined as [20,15,30,50,1,100]. Then list 1 is a sublist of list 2 because the numbers in list1 (15,1, and 100) appear in the same order. However, list [15,20,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.
I've gotten so far with the below code, but the code is not returning anything when I run it. I'm not sure what I am doing wrong here. Any hints of next steps would be great!
def sublist(lst1, lst2):
i = 0
for n in lst1:
while i < len(lst2):
if lst2[i] == n:
i+=1
return True
return False
print(sublist([15,1,100],[20,15,30,50,1,100]))
print(sublist([15,50,20],[20,15,30,50,1,100]))
Algorithm: Loop in through the first list element by element and for each element loop in through the second list and check if that element is present or not, count every such occurence using a variable count and maintain the index for second list accordingly. Finally check whether the value in count variable is equal to the length of the first list. If they are equal that means all the element of first array are present in second array and in sequence.
Have a look at the below code. I have put comments wherever required for better understanding.
def sublist(lst1, lst2):
# take a count variable
count = 0
# take an index variable
idx = 0
# loop in through first array
for x in lst1:
# loop in to the second array
while idx<len(lst2):
# check if elements are same or not
if (x==lst2[idx]):
# increase the count
count+=1
break
# increment the index
idx+=1
# return the flag value
return count==len(lst1)
Happy Learning!