When it is required to print the count of either peaks or valleys from a list, a simple iteration and a specific condition is placed.
Below is a demonstration of the same −
Example
my_list = [11,12, 24, 12, 36, 17, 28, 63] print("The list is :") print(my_list) my_result = 0 for index in range(1, len(my_list) - 1): if my_list[index + 1] > my_list[index] < my_list[index - 1] or my_list[index + 1] < my_list[index] > my_list[index - 1]: my_result += 1 print("The result is :") print(my_result)
Output
The list is : [11, 12, 24, 12, 36, 17, 28, 63] The result is : 4
Explanation
A list is defined and is displayed on the console.
An integer variable is initialized to 0.
The list is iterated over, and the consecutive indices are checked to see if they are less than or greater than each other.
If so, the integer is incremented by 1.
This is displayed as output on the console.