确定旅行者经过的山峰数量

2024-04-27 19:21:14 发布

您现在位置:Python中文网/ 问答频道 /正文

有必要根据数据来确定山顶有多少座,我们的旅行者到底穿越了多少座山。如果两个相邻的点与当前点的高度不高或不相等,则该点称为山峰。极端点不视为山峰(起点和终点)。 例如:

[1,2,3,2,1]
Answer: 1 peak

[1,2,3,3,2,1]
Answer: 0 peak

[1,2,5,6,4,3,4,2,1]
Answer: 2 peaks

我有麻烦比较两个相邻的峰值在一个循环,而且通过移动的峰值。或者我应该用什么函数?你知道吗

peaks = [1,2,3,4,5,6,3,1,4,5,7,4,3,12,67,85,34,23] #the peak points

for i in peaks:
    if i[0]>i[1][2]  # i stacked here, just dont know the right algorithm

Tags: the数据函数answerinforif高度
1条回答
网友
1楼 · 发布于 2024-04-27 19:21:14

只需检查data[i] > data[i - 1] and data[i] > data[i + 1],如果True,则增加计数器。你知道吗

def get_peak_count(data):
    count = 0
    l = len(data)
    for i in range(1, l - 1):
        if data[i - 1] < data[i] and data[i + 1] < data[i]:
            count += 1
    return count

print get_peak_count([1,2,3,2,1])
print get_peak_count([1,2,5,6,4,3,4,2,1])
print get_peak_count([1,2,3,3,2,1])
print get_peak_count([1,2,3,4,5,6,3,1,4,5,7,4,3,12,67,85,34,23])

下面是我测试它的链接:https://ideone.com/NNSeDG

相关问题 更多 >