L.Z
L.Z

Reputation: 33

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).

Upvotes: 3

Views: 7249

Answers (2)

Muhammad Kamal
Muhammad Kamal

Reputation: 1

longest_fragment = 0
current_fragment = 0

a = int(input())
last_input = a # why do I assign last_input here?
while a:
    if a == last_input:
        current_fragment += 1
    else:  # why is current_fragment assigned 1 in this clause?
        if current_fragment > longest_fragment:
            longest_fragment = current_fragment
            current_fragment = 1
    last_input = a
    a = int(input())

longest_fragment = max(longest_fragment, current_fragment) 
# why didn't i use max in the loop?
# why am I checking again down here anyway?

print('The longest fragment was:', longest_fragment)

Upvotes: 0

WGS
WGS

Reputation: 14169

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

Upvotes: 8

Related Questions