【问题标题】:Average length of sequence with consecutive values >100 (Python)连续值> 100的序列平均长度(Python)
【发布时间】:2020-04-18 05:38:15
【问题描述】:

我正在尝试识别数组中大于 100 的连续序列的长度。我使用以下代码找到了最长的序列,但需要更改才能找到平均长度。

def getLongestSeq(a, n): 
    maxIdx = 0
    maxLen = 0
    currLen = 0
    currIdx = 0
    for k in range(n): 
        if a[k] >100: 
            currLen +=1
             # New sequence, store 
            # beginning index. 
            if currLen == 1: 
                currIdx = k 
        else: 
            if currLen > maxLen: 
                maxLen = currLen 
                maxIdx = currIdx 
            currLen = 0

    if maxLen > 0: 
        print('Index : ',maxIdx,',Length : ',maxLen,) 
    else: 
        print("No positive sequence detected.") 

# Driver code 
arrQ160=resultsQ1['60s']
n=len(arrQ160)
getLongestSeq(arrQ160, n)

arrQ260=resultsQ2['60s']
n=len(arrQ260)
getLongestSeq(arrQ260, n)

arrQ360=resultsQ3['60s']
n=len(arrQ360)
getLongestSeq(arrQ360, n)

arrQ460=resultsQ4['60s']
n=len(arrQ460)
getLongestSeq(arrQ460, n)

输出

Index :  12837 ,Length :  1879
Index :  6179 ,Length :  3474
Index :  1164 ,Length :  1236
Index :  2862 ,Length :  617

【问题讨论】:

  • 尽可能避免索引。改用python优秀的迭代特性
  • 平均长度是什么意思?什么长度?

标签: python python-3.x


【解决方案1】:

这应该可行:

def get_100_lengths( arr ) :
    s = ''.join( ['0' if i < 100 else '1' for i in arr] )
    parts = s.split('0')
    return [len(p) for p in parts if len(p) > 0]

之后你可以计算一个平均值或做任何你喜欢的事情。

结果:

>>> get_100_lengths( [120,120,120,90,90,120,90,120,120] )
[3, 1, 2]

【讨论】:

  • 哇,这个方法我没想过,这个挺有意思的
  • 如果我现在想知道每个开始的索引以便我可以计算时间之间的时间?所以对于你上面的例子,我会得到 [0:3, 5:1, 7:2]
  • @Jake 你可能想问另一个问题,因为这似乎是一个有点不同的问题,需要不同的解决方案
【解决方案2】:

这可能有点棘手。您想使用一个变量来跟踪长度总和,使用一个变量来跟踪序列发生的次数。 我们可以判断当前数字

def getLongestSeq(array): 
    total_length = total_ct = 0
    last_is_greater = False 
    for number in array:
        if number > 100: 
            total_length += 1 
            last_is_greater = True
        elif number<100 and last_is_greater:
            total_ct += 1 
            last_is_greater = False 
    return round(total_length / total_ct) 

未测试此代码,如有问题请评论

【讨论】:

  • 感谢您的回复和花费的时间!我最终使用了 lenik 提供的方法,效果很好。
【解决方案3】:

你想找到所有的序列,取它们的长度,然后求平均值。这些步骤中的每一个都相对简单。

items = [1, 101, 1, 101, 101, 1, 101, 101, 101, 1]

查找序列:使用groupby

from itertools import groupby
groups = groupby(items, lambda x: x > 100)  # (False, [1]), (True, [101]), ...

查找长度(小心,可迭代的可迭代对象不是列表):

lens = [len(g) for k, g in groups if k]  # [1, 2, 3]

求平均值(假设至少有一个):

avg = float(sum(lens)) / len(lens)  # 2.0

【讨论】:

    猜你喜欢
    • 2020-05-29
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多