H.K
H.K

Reputation: 241

How to find the maximum consecutive occurrences of a number in python

I want to find out the maximum number of consecutive occurrences of a number in python. I am using the following code from stack overflow.

from itertools import groupby
b= [1,2,45,55,5,4,3,2,5,5,6,5456,5456,5456,7,67,6,6]

print(b)

def occurrence():
    occurrence, num_times = 0, 0
    for key, values in groupby(b, lambda x : x):
        val = len(list(values))
        if val >= occurrence:
            occurrence, num_times =  key, val
    return occurrence, num_times

occurrence, num_times = occurrence()
print("%d occurred %d times" % (occurrence, num_times))

I get the following answer:

5 occurred 2 times

The answer should be 5456 because it occurred 3 times. Can any body help me to resolve the issue?

Upvotes: 1

Views: 2156

Answers (3)

PM 2Ring
PM 2Ring

Reputation: 55469

You can simplify that code by using the built-in max function to find the maximum num_times.

from itertools import groupby

b = [1, 2, 45, 55, 5, 4, 3, 2, 5, 5, 6, 5456, 5456, 5456, 7, 67, 6, 6]

num_times, occurrence = max((len(list(values)), key) for key, values in groupby(b))
print("%d occurred %d times" % (occurrence, num_times))

output

5456 occurred 3 times

There's no need to give groupby that inefficient lambda x: x: if you don't give it a key function it uses the identity function by default.


FWIW, there's a more efficient way to calculate the length of a groupby group. It doesn't matter here, but it's handy when the groups are large. Rather than converting the group to a list & getting its length, we can loop over the group and use the built-in sum to count the items in the group. Just change

len(list(values))

to

sum(1 for _ in values)

Upvotes: 2

hiro protagonist
hiro protagonist

Reputation: 46849

the only change you need is

if val >= num_times:

your code is comparing the length of the current group with the last key.

this returns the last item with maximal consecutive occurrence (if there were three times 5 later in the list this would be selected).

Upvotes: 2

blhsing
blhsing

Reputation: 106455

You can use the following generator expression:

print('{1} occurred {0} times'.format(*max((len(list(g)), k) for k, g in groupby(b))))

This outputs:

5456 occurred 3 times

Upvotes: -1

Related Questions