从列表中打印峰值或谷值的Python程序
给定一个 List,下面的文章展示了计算 peak(x > y < z) 或 Valley(x < y > z) 元素的方法。
Input : test_list = [1, 2, 4, 2, 6, 7, 8, 3]
Output : 3
Explanation : (2, 4, 2), (4, 2, 6), (7, 8, 3) are peaks and valleys.
Input : test_list = [1, 2, 4, 5, 3, 2]
Output : 1
Explanation : (4, 5, 3) is peak.
方法一:使用循环
在这里,我们迭代每个元素并检查它的下一个和上一个元素是否小于或大于当前元素。如果找到,则计数器递增。
Python3
# initializing list
test_list = [1, 2, 4, 2, 6, 7, 8, 3]
# printing original list
print("The original list is : " + str(test_list))
res = 0
for idx in range(1, len(test_list) - 1):
if test_list[idx + 1] > test_list[idx] < test_list[idx - 1] or test_list[idx + 1] < test_list[idx] > test_list[idx - 1]:
res += 1
# printing result
print("Peaks and Valleys count : " + str(res))
Python3
# initializing list
test_list = [1, 2, 4, 2, 6, 7, 8, 3]
# printing original list
print("The original list is : " + str(test_list))
# one-liner alternative
res = len([test_list[idx] for idx in range(1, len(test_list) - 1) if test_list[idx + 1] >
test_list[idx] < test_list[idx - 1] or test_list[idx + 1] < test_list[idx] > test_list[idx - 1]])
# printing result
print("Peaks and Valleys count : " + str(res))
输出:
The original list is : [1, 2, 4, 2, 6, 7, 8, 3]
Peaks and Valleys count : 3
方法 2:使用列表推导和len()
在这里,我们使用列表推导来执行获取峰值和谷值的任务,然后使用 len() 来计算确切的计数。
蟒蛇3
# initializing list
test_list = [1, 2, 4, 2, 6, 7, 8, 3]
# printing original list
print("The original list is : " + str(test_list))
# one-liner alternative
res = len([test_list[idx] for idx in range(1, len(test_list) - 1) if test_list[idx + 1] >
test_list[idx] < test_list[idx - 1] or test_list[idx + 1] < test_list[idx] > test_list[idx - 1]])
# printing result
print("Peaks and Valleys count : " + str(res))
输出:
The original list is : [1, 2, 4, 2, 6, 7, 8, 3]
Peaks and Valleys count : 3