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.
>>>defgen(lst, pat):... size = len(pat)... size_l = len(lst)...for i inrange(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 list
class
Solution 2:
How about this?
deffind_sub(lst):
returnnext(sub for sub inrange(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"