gpt4 book ai didi

python - 如何查找和打印趋势点变化

转载 作者:太空宇宙 更新时间:2023-11-04 11:12:47 24 4
gpt4 key购买 nike

我正在研究的逻辑:

我正在尝试打印出变化点的结果。

趋势变化点是数组改变方向并从升序变为降序或从降序变为升序的那些点。

我应该得到:11 8 5 10 但我只得到了其中的一部分。 **我的方法是正确的方法吗?*

numberss = [1,4,9,11,8,3,2,5,10]
trendpoints(numberss,len(numberss))

def trendpoints(number_array, length):
print("length", length)
print(number_array)
# -1 on the array because we dont need to jump to the last number (fake fix)
for num in range(1, length-1):
# check last, current and next
# if current greater then current and less then next
# [1,4,9,11,8,3,2,5,10]
# 11 hit 8 CHANGE UP print both
if num <= length:
#print(number_array[num-1])
#print(number_array[num])
#print(number_array[num+1])

# 9 11 8
# 11 > 9
# 11 < 8

# 2 5 10
# 2 < 5
# 10 > 5
if ((number_array[num] > number_array[num-1] and number_array[num] > number_array[num+1])
or (number_array[num] < number_array[num-1] and number_array[num] > number_array[num+1])):
#print("CHANGE")
print(number_array[num])
#print(number_array[num+1])
print("---")

我的结果:

length 9
[1, 4, 9, 11, 8, 3, 2, 5, 10]
---
---
11
---
8
---
3
---
---
---

最佳答案

如评论中所述,11 和 2 是唯一预期的解决方案。这是一个使用列表理解的简短解决方案:(假设没有重复数字)

def trendpoints(number_array, length):
diff_array = [number_array[i] - number_array[i - 1] for i in range(1, length)]
trend_array = [number_array[i] for i in range(1, length - 1) if diff_array[i] * diff_array[i - 1] <= 0]
return trend_array

关于python - 如何查找和打印趋势点变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57811470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com