Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program – Print the count of either peaks or valleys from a list
When it is required to count peaks (values higher than both neighbors) or valleys (values lower than both neighbors) from a list, we use iteration with specific conditions to compare each element with its adjacent elements.
Understanding Peaks and Valleys
A peak is an element that is greater than both its left and right neighbors. A valley is an element that is smaller than both its left and right neighbors. We only check elements that have both left and right neighbors (excluding first and last elements).
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 count of peaks and valleys is:")
print(my_result)
The list is: [11, 12, 24, 12, 36, 17, 28, 63] The count of peaks and valleys is: 4
How It Works
The algorithm checks each element (except first and last) against its neighbors:
Valley condition:
my_list[index + 1] > my_list[index] - current element is smaller than both neighborsPeak condition:
my_list[index + 1] my_list[index - 1]- current element is greater than both neighbors
In our example: 24 (peak), 12 (valley), 36 (peak), 17 (valley) = 4 total.
Separate Count for Peaks and Valleys
my_list = [11, 12, 24, 12, 36, 17, 28, 63]
peaks = 0
valleys = 0
for index in range(1, len(my_list) - 1):
if my_list[index] > my_list[index - 1] and my_list[index] > my_list[index + 1]:
peaks += 1
print(f"Peak found at index {index}: {my_list[index]}")
elif my_list[index] < my_list[index - 1] and my_list[index] < my_list[index + 1]:
valleys += 1
print(f"Valley found at index {index}: {my_list[index]}")
print(f"\nTotal peaks: {peaks}")
print(f"Total valleys: {valleys}")
print(f"Total peaks and valleys: {peaks + valleys}")
Peak found at index 2: 24 Valley found at index 3: 12 Peak found at index 4: 36 Valley found at index 5: 17 Total peaks: 2 Total valleys: 2 Total peaks and valleys: 4
Conclusion
To count peaks and valleys, iterate through the list (excluding endpoints) and compare each element with its neighbors. Use logical conditions to identify when an element is greater than (peak) or less than (valley) both adjacent elements.
