Python在整数列表中找到重复序列? [英] Python finding repeating sequence in list of integers?

查看:268
本文介绍了Python在整数列表中找到重复序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表,每个列表都有一个重复序列.我正在尝试计算列表中重复整数序列的长度:

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,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]

哪个会返回:

list_a count = 4 (for [111,0,3,1])

list_b count = 2 (for [67,4])

list_c count = 10 (for [1,2,3,4,5,6,7,8,9,0])

任何建议或提示都将受到欢迎.我现在正在尝试使用re.compile来解决这个问题,但是,它不太正确.

Any advice or tips would be welcome. I'm trying to work it out with re.compile right now but, its not quite right.

推荐答案

通过迭代序列长度的2到一半之间的猜测来猜测序列长度.如果未发现任何模式,则默认返回1.

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

(预期):

4
2
10
1

根据要求,此替代方法可提供最长的重复序列.因此,它将为list_b返回4.唯一的变化是guess = x而不是return x

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

这篇关于Python在整数列表中找到重复序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆