Skip to content Skip to sidebar Skip to footer

Finding Integer Pattern From A List

I have a list of numbers, for example: list= [1, 2, 4, 1, 2, 4, 1, 2, 4] You can see the obvious repeating pattern of 1,2,4 I'm trying to find a way to go through that list to det

Solution 1:

You can use a generator function to split your list into chunks.

>>> def gen(lst, pat):
...     size = len(pat)
...     size_l = len(lst)
...     for i in range(0, size_l, size):
...         yield lst[i:i+size]
... 
>>> lst = [1, 2, 4, 1, 2, 4, 1, 2, 4]
>>> pat = [1, 2, 4]
>>> len(list(gen(lst, pat)))
3

Also don't use "list" as variable's name it will shadow the built-in listclass


Solution 2:

How about this?

def find_sub(lst):
    return next(sub for sub in range(len(lst), 0, -1)
                    if lst == mylist[:sub] * (len(lst) / sub))

find_sub([1, 2, 4, 1, 2, 4, 1, 2, 4]) # returns 3
find_sub([1, 2, 1, 2, 1, 2, 1, 2]) # returns 2
find_sub([1, 1, 1]) # returns 1
find_sub([1, 2, 3]) # returns 3
find_sub([1, 2, 3, 1, 2, 3, 1]) # returns 7

Post a Comment for "Finding Integer Pattern From A List"