Find all possible patters in list of no and the position of the pattern break

42 Views Asked by At

input has list of nos output has all the possible pattern occurring and the position where the pattern break

input

[1,2,3,1,2,3,1,2,3,4,1,2,3,10,5,6,4,5,6,8,4,5,6,12,2,3]

output

[1,2,3]: 10th position and 14th

[4,5,6]:20th position and 24th

[1,2,3] and [4,5,6] all possible patter the position where the pattern breaks 10,14 for [1,2,3] and 20 and 24 for [4,5,6]

1

There are 1 best solutions below

0
R. Baraiya On

Code:

import more_itertools as mit
from ast import literal_eval
l= [1,2,3,1,2,3,1,2,3,4,1,2,3,10,5,6,4,5,6,8,4,5,6,12,2,3]

#split the list by sequences

seq = [list(group) for group in mit.consecutive_groups(l)]

#find duplicate lists

uni = set([str(s) for s in seq if seq.count(s)>1])

#create new dictionary with empty lists to store output

dic = {u:[] for u in uni}

#main code, apply nested loop over uni and seq, and compare the both lists, in simple term first try to the next not same list from [1,2,3] so first outcome will be [1,2,3,4] take the last element 4 and find the index value of it from input list plus 1 will be the output.

[dic[v].append(l.index(s[-1])+1) for i, v in enumerate(uni) for j, s in enumerate(seq) if str(seq[j-1])==v and s!=literal_eval(v)]

Output:

{'[1, 2, 3]': [10, 14], '[4, 5, 6]': [20, 24]}