Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
936 views
in Technique[技术] by (71.8m points)

python - Find maximum length of consecutive repeated numbers in a list

My question is how to find the maximum length of consecutive repeated numbers (or elements in general) in a list. I wrote the following function which works fine but I was wondering if there's a better way to do this or improve my code.

def longest(roll):
    '''Return the maximum length of consecutive repeated elements in a list.'''
    i = 0
    M = 0   # The maximum length
    while 0 <= i < len(roll):
        c = 1  # Temporarily record the length of consecutive elements
        for j in range(i+1, len(roll)):
            if roll[j] != roll[i]:
                i = j
                break
            c += 1
            i += 1    
        if c > M:
            M = c
        if i == len(roll) - 1:
            break
    return M  

By maximum length I mean the following:
[1, 1, 2, 2, 2, 4] should return 3 (2 repeated 3 times);
[1, 2, 1, 2, 1] should return 1 (1 and 2 only repeated once).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use itertools.

In [8]: import itertools

In [9]: z = [(x[0], len(list(x[1]))) for x in itertools.groupby(a)]

In [10]: z
Out[10]: [(1, 2), (2, 3), (3, 1)]

Tuples are in (item, count) format. If there are multiple runs of a given number, this will group them accordingly as well. See below.

In [11]: a = [1,1,1,1,1,2,2,2,2,2,1,1,1,3,3]

In [12]: z = [(x[0], len(list(x[1]))) for x in itertools.groupby(a)]

In [13]: z
Out[13]: [(1, 5), (2, 5), (1, 3), (3, 2)]

Getting the max value isn't that hard from here.

In [15]: max(z, key=lambda x:x[1])[1]
Out[15]: 5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...