IndirectWombat
IndirectWombat

Reputation: 33

Count longest streak of >0 in a Python list Python

I have a list of float values, something like [-2.4, -1.3, -3.8, -1.9, 5.0, 0.6, 2.9, 1.9, 4.7, 3.5, 6.9, 1.5, -4.2, 3.7, 2.1, 6.6, 7.0, -4.6, -4.9].

What I need and trying to do is count the longest streak of values >0.

Tried doing it through for loop, but it gives only a total count, and through itertools.groupby, but I'm still getting only values.

for i, x in groupby(mintemps):
    if float(i >= 0):
        print(len(list(x)))

Any help would be greatly appreciated.

Upvotes: 3

Views: 2511

Answers (4)

ikkuh
ikkuh

Reputation: 4603

The groupby method takes a key argument to specify a function to compute key value for each element. We can use this to create a one-liner:

max(len(list(g)) for k, g in groupby(mintemps, key=lambda x: x > 0) if k)

Upvotes: 1

Albin Paul
Albin Paul

Reputation: 3419

If you use numpy and itertools this turns out to be pretty fast ,

I converted the list to a boolean array in which the values are indicated if an element in greater than 0 and thne fed it to itertools.groupby to get its maximum consecutive value , the bit value is True or False.

import numpy as np
import itertools
narr=np.array([-2.4, -1.3, -3.8, -1.9, 5.0, 0.6, 2.9, 1.9, 4.7, 3.5, 6.9, 1.5, -4.2, 3.7, 2.1, 6.6, 7.0, -4.6, -4.9])

def max_runs_of_ones(bits):
    maxvalue=0
    for bit, group in itertools.groupby(bits):
        if bit: 
            maxvalue=max(maxvalue,sum(group))
    return maxvalue
print(narr)

print("maximum value is",max_runs_of_ones(narr>0))

OUTPUT

[-2.4 -1.3 -3.8 -1.9  5.   0.6  2.9  1.9  4.7  3.5  6.9  1.5 -4.2  3.7
  2.1  6.6  7.  -4.6 -4.9]

maximum value is 8

Upvotes: 2

Frayal
Frayal

Reputation: 2161

you can also do the following. Removing the max will get you all the length of positive numbers sequences:

np.max([ len(l) for l in ("".join(["p" if i>0 else 'n' for i in a]).split('n')) if l])

Upvotes: 0

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11073

Try this:

a = [-2.4, -1.3, -3.8, -1.9, 5.0, 0.6, 2.9, 1.9, 4.7, 3.5, 6.9, 1.5, 3.7, 2.1, 6.6, 7.0, -4.6, -4.9]


l=[]
z=0
for i in a:
    if i > 0:
        z=z+1
    else:
        l.append(z)
        z=0

Then the max(l) will be the answer.

Upvotes: 1

Related Questions