[英]Finding the longest string of consecutive positive numbers in a list
I have a series: 我有一系列:
series = [0,2, 1, -2, 0, 0, 2, 3 ,1, 7]
What is the most time efficient way of finding the length of the longest string of consecutive positive numbers? 查找连续正数最长字符串长度的最省时方法是什么? In this example, it must be 4 (length of [2, 3, 1, 7]) 在此示例中,它必须为4([2、3、1、7]的长度)
You could use itertools.groupby
to group positive numbers, then use max
to find the longest run of such numbers 您可以使用itertools.groupby
对正数进行分组,然后使用max
查找最长的此类数
>>> from itertools import groupby
>>> max((list(g) for k, g in groupby(series, key=lambda i: i > 0)), key=len)
[2, 3, 1, 7]
Solution from pandas
pandas
解决方案
s=pd.Series(np.sign(np.array(series)))
pd.crosstab(s,s.diff().ne(0).cumsum())
Out[495]:
col_0 1 2 3 4 5
row_0
-1 0 0 1 0 0
0 1 0 0 2 0
1 0 2 0 0 4
pd.crosstab(s,s.diff().ne(0).cumsum()).max(1)
Out[494]:
row_0
-1 1
0 2
1 4
dtype: int64
In terms of most time efficient it's going to be hard to beat a simple loop: 从最省时的角度来看,很难克服一个简单的循环:
def maxPositiveRun():
count = 0
maxVal = 0
for n in series:
if n > 0:
count +=1
if count > maxVal:
maxVal = count
else:
count = 0
return maxVal
This assumes by most time efficient you mean time for the function to run rather than the time to understand or write the function. 假设最节省时间的意思是您要运行该功能的时间,而不是理解或编写该功能的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.