【发布时间】:2025-12-04 23:35:01
【问题描述】:
独自跑步,需要一些帮助。如果您有一系列数字,并且想要计算值跨越障碍的次数,您会怎么做?
series = [1, 6, 2, 4, 1, 9, 2]
series.hit_counts(upper=7, middle=5, lower=3) #returns 3
详情
1 -> 6 = +1 (Going from 1 to 6 hits the lower and middle threshold)
6 -> 2 = +0 (The high value, 6, never reached the upper threshold although it crosses the middle)
2 -> 4 = +0 (2 is below the lower threshold but has not hit the middle)
4 -> 1 = +0 (The series still has not reached the middle threshold)
1 -> 9 = +1 (The series hit the middle threshold)
9 -> 2 = +1 (The series has hit the high and middle thresholds)
hit_counts:计算值达到上限或下限然后超过中间阈值的次数。
上限:7
中限:5
下限:3
有问题的方法将返回3。任何想法,将不胜感激。
【问题讨论】:
-
当您将更改计为阈值命中时并不完全清楚。我最初的猜测是,只有当
a超出upper..lower范围并且a..b包含middle时,[a, b] 才算作命中。正确的?此外,您的详细信息中有一个额外的步骤9 -> 2,它不会出现在您的初始数组中。 -
评论好像被截断了?有什么不清楚的请告诉我
-
回车太早,现在编辑。
-
谢谢。更新了问题。仅当先前的值达到上限或下限阈值时,计数才会增加。因此,该方法必须考虑的不仅仅是 [previous_value, current_value]。当我尝试自己实现它时,我最终使用了一个变量来保存状态(它是否达到了上限或下限)。
-
所以实际上我们只需要计算我们超过两个阈值的对吗?
标签: ruby loops iterator logic time-series