'How to return pattern from 2 integer list

Question: I want to return the similarity of pattern from 2 integer list input,

Input example :

6 6

2 3 6 8 10 15

3 8 2 15 3 4

And the output should be:

3

[3, 8, 15]

and here is my code :

Code:

def main():
  q_element = [] 
  list1=[]
  list2=[]
  
  q_element = [int(item) for item in input("Quantity of each list : ").split()]
  list1 = [int(item) for item in input("Enter list 1    : ").split()]
  list2 =  [int(item) for item in input("enter list 2 : ").split()] 

  result = common_elements(list1, list2)
  if len(result) == 0 :
    return "No pattern"
  else:
    if len(list1) == q_element[0] and len(list2) == q_element[1]:
      print(len(result));
      return result;
    else :
      return "Your input doesn't match the quantity";

def common_elements(list1, list2):
    result = []
    for element in list1:
        if element in list2:
            result.append(element)
    return result

main()

Output:

Quantity of each list : 6 6
Enter list 1    : 2 3 6 8 10 15
enter list 2 : 3 8 2 15 3 4
4
[2, 3, 8, 15]

This is the example of the output (the red marker)

This is the example of the output (the red marker one)

I use the test input from above but the output is still not the same, can anyone help?



Solution 1:[1]

I dont know if I understood your question correctly, but looking at the example you gave you can change the common_elements function in the following way:

def common_elements(list1, list2):
    result = []
    for element in list1:
        if element in list2:
            result.append(element)
            list2 = list2[list2.index(element)+1:]
    return result    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aishwarya Patange