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

时间:2019-06-16 09:32:11

标签: 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

1 个答案:

答案 0 :(得分:1)

只需检查是否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