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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With