Home > Mobile >  find repeating patterns of same number in a list of numbers
find repeating patterns of same number in a list of numbers

Time:05-11

I'm trying to find the repeating pattern of same number in a list numbers. eg.

flag_list = [6, 4, 4, 20, 4, 4, 4, 4, 22, 0, 0, 0, 0, 0, 0, 16, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16]

Desired output: it will be a list of lists of all repeating numbers. eg.

repeating_list = [[4, 4],
                  [4, 4, 4, 4],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0],
                  [16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                  ]

I tried in these lines:

main_list = []
temp = []
for i in range(0,len(flag_list)):
   
    if flag_list[i-1]==flag_list[i]:
        if flag_list[i-1] not in temp:
            temp.append(flag_list[i-1])
        temp.append(flag_list[i])
 
    main_list.append(temp)
    temp.clear()

Please share any resource regarding this that'll be a big help. Thanks

CodePudding user response:

Ideally, use itertools.groupby:

flag_list = [6, 4, 4, 20, 4, 4, 4, 4, 22, 0, 0, 0, 0, 0, 0, 16, 0, 0,
             16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
             16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16]

from itertools import groupby

[G for _,g in groupby(flag_list) if len(G:=list(g))>1]

NB. this code uses an assignment expression and requires python ≥ 3.8

or using extended iterable unpacking as suggested by @wjandrea, compatible with python ≥ 3.0:

[g for _k, (*g,) in groupby(flag_list) if len(g) > 1]

output:

[[4, 4],
 [4, 4, 4, 4],
 [0, 0, 0, 0, 0, 0],
 [0, 0],
 [16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]
variant format

you can easily "compress" the output if the form (value, number_repeats) using:

[(n, len(G)) for n,g in groupby(flag_list) if len(G:=list(g))>1]

output:

[(4, 2), (4, 4), (0, 6), (0, 2), (16, 19), (0, 46)]
  • Related