Search code examples
pythonpython-3.xlistcomparenested-loops

python - Comparing two lists to see if one occurs in another consecutively


I've been trying to make a function that can take two lists of any size (say, list A and list B) and sees if list B occurs in list A, but consecutively and in the same order. If the above is true, it returns True, else it'll return False

e.g.

A:[9,0,**1,2,3,4,5,6,**7,8] and B:[1,2,3,4,5,6] is successful

A:[1,2,0,3,4,0,5,6,0] and B:[1,2,3,4,5,6] is unsuccessful.

A:[1,2,3,4,5,6] and B [6,5,3,2,1,4] fails because despite having the same 
 numbers, they aren't in the same order

I've tried doing this using nested loops so far and am a bit confused as to where to go


Solution

  • Just try this:

    L1 = [9,0,1,2,3,4,5,6,7,8]
    L2 = [1,2,3,4,5,6]
    c = 0
    w = 0
    for a in range(len(L2)):
       for b in range(w+1, len(L1)):
          if L2[a] == L1[b]:
            c = c+1
            w = b
            break
          else:
            c = 0
        if c == len(L2):
           print('yes')
           break
    

    Here you check if the element of l2 is in l1 and if so breaks the first loops remember where you left and of the next element of l2 is the same as the next element of l1 and so on.

    And the last part is to check if this happened as much times as the length of l2. if so then you know that the statement is correct!