Python - 测量列表中某个值的最长子序列,并具有误差容忍度

标签 python

给定整数列表[0,0,0,1,1,0,2,2,0,1,0,0,2,1,2,2,2,2,1, ...],我需要计算其中 x% 的元素为 n 的元素的最长子序列,即存在一个容差,其中包含除 n 之外的小于 1 - x% 值的子序列仍然是被视为 n 的完整子序列。

我使用以下单行代码来获取所有值为 n 的最长子序列,但我不知道从这里开始:

longest_subsequence_0 = max((len(l) for n, l in itertools.groupby(list) if n == 0))

如果有人能引导我走向正确的方向,我将不胜感激:D

最佳答案

只是一个改变大小并计算百分比的滑动窗口。如果高于阈值,则记录窗口大小(如果该窗口大小大于先前存储的窗口大小)。

def longest_sub(list, n, threshold):
    largest_window = 0
    for i in range(len(list)+1): # from i 
        for j in range(i+1,len(list)+1): # to j
            window_len = len(list[i: j]) # store window size
            if window_len > largest_window: # if inspected window > largest found yet
                if list[i:j].count(n)/window_len*100 > threshold: # if percentage above threshold
                    largest_window = window_len # new largest_window
    return largest_window

longest_sub([0,0,0,1,1,0,2,2,0,1,0,0,2,1,2,2,2,2,1], 0, 30) # 9 
longest_sub([0,0,0,1,1,0,2,2,0,1,0,0,2,1,2,2,2,2,1], 0, 80) # 3

关于Python - 测量列表中某个值的最长子序列,并具有误差容忍度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60380013/

相关文章:

python - 如何在 pygame 中使图 block map 滚动?

python - 使用递归查看随机列表时如何跟踪偶数的数量

python - Django admin模型复数模式全局设置,不添加后缀 's'

python - 在 Python 中绘制动画 slider

python - 如何在 gtk.ScrolledWindow 内的 GtkTreeView 中显示列标题?

python - 为什么使用force_unicode?

python - 在 Python 中将日期时间转换为 protobuf 时间戳

python - SQLAlchemy 将值插入到反射表中会导致所有 NULL 条目

python - Django .update 不调用覆盖保存?

python - 棉花糖不报错