Question

In: Computer Science

I am working on exercise 5.48 from Introduction to Computing using python (Author: Perkovic). Problem Question:...

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]))

Solutions

Expert Solution

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!


Related Solutions

I am working on this problem for the company AT & T and am not sure...
I am working on this problem for the company AT & T and am not sure how to start it. Draw a chart of the main inter-organizational linkage mechanisms (e.g., long -term contacts, strategic alliances, mergers) that your organization uses to manage its symbiotic resource interdependencies. Using resource dependence theory and transaction cost theory, discuss why the organization to manage its interdependencies in this way. Do you think the organization has selected the most appropriate linkage mechanisms? Why or why...
I am building a tik tac toe board using python and the function I am using...
I am building a tik tac toe board using python and the function I am using is not working to check to see if the board is full. I'll include the code for the board and the function to check if it is full. X's and O's are being inserted and the function is suppose to stop running when is_full(board) returns True. ch is either x or o board = []    for i in range(3):     board.append([])     for j...
I am working on routing path and subnet. The question is I am given with source...
I am working on routing path and subnet. The question is I am given with source 10.1.240.240 and the destinations is 10.2.240.240. How is the packet traveling?
Chapter 7, Problem 3PE from Introduction to Programming using Python by Y. Daniel Liang. Problem (The...
Chapter 7, Problem 3PE from Introduction to Programming using Python by Y. Daniel Liang. Problem (The Account class) Design a class named Account that contains: ■ A private int data field named id for the account. ■ A private float data field named balance for the account. ■ A private float data field named annualInterestRate that stores the current interest rate. ■ A constructor that creates an account with the specified id (default 0), initial balance (default 100), and annual...
It is a C++ introduction exercise and I am a rookie. Please contain detailed reasons and...
It is a C++ introduction exercise and I am a rookie. Please contain detailed reasons and explanations and I would appreciate any help you can provide. When we pass parameters to functions by value or by reference, we're doing different things; the end result will not necessarily be the same. And, of course, it's wise for us to understand exactly how the results will be different. But another angle we need to consider is why we need to have these...
I am a student taking python programming. Can this problem be modified using the define main...
I am a student taking python programming. Can this problem be modified using the define main method, def main()? #Define showExspenses function def showExpenses(loan,insure,gas,oil,tyres,maintenance): expense=loan+insure+gas+oil+tyres+maintenance #Print monthly and yearly automobile operating expenses print("\nTotal Monthly expenses for operating expenses you entered = ",expense) print(f"\nTotal Yearly expenses for operating expenses you entered = 12 *",expense,f"= {expense*12:,}") #yearly expenses loan=int(input("Enter Loan :")) insure=int(input("Enter Insurance :")) gas=int(input("Enter Gas :")) oil=int(input("Enter Oil :")) tyres=int(input("Enter Tyres :")) maintenance=int(input("Enter Maintenance:")) showExpenses(loan,insure,gas,oil,tyres,maintenance)
I am currently working on this problem. It says it is wrong, and I was wondering...
I am currently working on this problem. It says it is wrong, and I was wondering if someone could correct my code to where its ouput is as followed. Expected Output: 6↵ 5↵ 4↵ 3↵ 2↵ 1 Actual Output: 9↵ 8↵ 7↵ 6↵ 5↵ 4↵ 3↵ 2↵ 1↵ 0↵ 9.10: Reverse Array Write a function that accepts an int array and the array’s size as arguments. The function should create a copy of the array, except that the element values...
Needs to be coded in Python. Hello i am working on a project for my computer...
Needs to be coded in Python. Hello i am working on a project for my computer programming course and i am having trouble with one part. The code needs to be able to produce two versions of an output given inputs by the user. for instance. Here is the code i have to produce the following output. The input from the user are num1 num2 and asc which is just asking if they want the output to be ascending or...
Attached is the problem I am working on I have to use phantoms, and i have...
Attached is the problem I am working on I have to use phantoms, and i have already completed steps p and H, I need help help with step A , which is to "state and check the assumptions for the hypothesis test", I think the correct hypothesis test to use would be the 2 sample t test, but im not sure. The number of cell phones per 100 residents in countries in Europe is given in table #9.3.9 for the...
Here is the problem I am working on. I need to write a py program that:...
Here is the problem I am working on. I need to write a py program that: Calculates a Cartesian Product Output, A x B of 2 lists. I want to limit each list to 5 numbers. It is kind of working, but I can't help think that there is a simpler way to express this problem. Please advise... Here is my code: def CartesianProductOutput(A,B):     lst = []     for x in A:         t = []         t.append(x)         for y in B:             temp...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT