What is the best way to find the period of a (repeating) list in Mathematica?

前端 未结 9 1351
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 15:12

What is the best way to find the period in a repeating list?

For example:

a = {4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2}

has repeat

9条回答
  •  攒了一身酷
    2021-01-01 16:07

    I don't know how to solve it in mathematica, but the following algorithm (written in python) should work. It's O(n) so speed should be no concern.

    def period(array):
        if len(array) == 0:
            return False
        else:
            s = array[0]
            match = False
            end = 0
            i = 0
    
            for k in range(1,len(array)):
                c = array[k]
    
                if not match:
                    if c == s:
                        i = 1
                        match = True
                        end = k
                else:
                    if not c == array[i]:
                        match = False
                    i += 1
    
            if match:
                return array[:end]
            else:
                return False
    
    # False         
    print(period([4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2,1]))
    # [4, 5, 1, 2, 3]            
    print(period([4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2]))
    # False
    print(period([4]))
    # [4, 2]
    print(period([4,2,4]))
    # False
    print(period([4,2,1]))
    # False
    print(period([]))
    

提交回复
热议问题