Python在整数列表中查找重复序列?

时间:2012-07-08 18:48:31

标签: python list sequence

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

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解决这个问题,但是,它不太正确。

3 个答案:

答案 0 :(得分:11)

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

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

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

答案 1 :(得分:0)

我采用了 Maria 的更快、更符合 stackoverflow 的答案,并让它首先找到了最大的序列:

def guess_seq_len(seq, verbose=False):
    seq_len = 1
    initial_item = seq[0]
    butfirst_items = seq[1:]
    if initial_item in butfirst_items:
        first_match_idx = butfirst_items.index(initial_item)
        if verbose:
            print(f'"{initial_item}" was found at index 0 and index {first_match_idx}')
        max_seq_len = min(len(seq) - first_match_idx, first_match_idx)
        for seq_len in range(max_seq_len, 0, -1):
            if seq[:seq_len] == seq[first_match_idx:first_match_idx+seq_len]:
                if verbose:
                    print(f'A sequence length of {seq_len} was found at index {first_match_idx}')
                break
    
    return seq_len

答案 2 :(得分:-1)

这对我有用。

def repeated(L):
    '''Reduce the input list to a list of all repeated integers in the list.'''
    return [item for item in list(set(L)) if L.count(item) > 1]

def print_result(L, name):
    '''Print the output for one list.'''
    output = repeated(L)
    print '%s count = %i (for %s)' % (name, len(output), output)

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_result(list_a, 'list_a')
print_result(list_b, 'list_b')
print_result(list_c, 'list_c')

Python的set()函数会将列表转换为集合,这是一种只能包含任何给定值之一的数据类型,就像代数中的集合一样。我将输入列表转换为集合,然后返回到列表,将列表缩减为仅其唯一值。然后,我测试了每个值的原始列表,看它是否多次包含该值。我返回了所有重复项的列表。其余代码仅用于演示目的,以表明它有效。

编辑:语法高亮不喜欢我的文档字符串中的撇号。