Python finding repeating sequence in list of integers?

后端 未结 2 550
花落未央
花落未央 2020-12-06 03:01

I have a list of lists and each list has a repeating sequence. I\'m trying to count the length of repeated sequence of integers in the list:

list_a = [111,0         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 04:08

    Guess the sequence length by iterating through guesses between 2 and half the sequence length. If no pattern is discovered, return 1 by default.

    def guess_seq_len(seq):
        guess = 1
        max_len = len(seq) / 2
        for x in range(2, max_len):
            if seq[0:x] == seq[x:2*x] :
                return x
    
        return guess
    
    list_a = [111,0,3,1,111,0,3,1,111,0,3,1] 
    list_b = [67,4,67,4,67,4,67,4,2,9,0]
    list_c = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,23,18,10]
    
    print guess_seq_len(list_a)
    print guess_seq_len(list_b)
    print guess_seq_len(list_c)
    print guess_seq_len(range(500))   # test of no repetition
    

    This gives (as expected):

    4
    2
    10
    1
    

    As requested, this alternative gives longest repeated sequence. Hence it will return 4 for list_b. The only change is guess = x instead of return x

    def guess_seq_len(seq):
        guess = 1
        max_len = len(seq) / 2
        for x in range(2, max_len):
            if seq[0:x] == seq[x:2*x] :
                guess = x
    
        return guess
    

提交回复
热议问题