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 – Check alternate peak elements in List
When it is required to check the alternate peak elements in a list, a function is defined that iterates through the list, compares adjacent elements, and returns the index of a peak element. A peak element is an element that is greater than or equal to its neighbors.
Example
Below is a demonstration of finding peak elements in a list ?
def find_peak(my_array, array_length):
if (array_length == 1):
return 0
if (my_array[0] >= my_array[1]):
return 0
if (my_array[array_length - 1] >= my_array[array_length - 2]):
return array_length - 1
for i in range(1, array_length - 1):
if (my_array[i] >= my_array[i - 1] and my_array[i] >= my_array[i + 1]):
return i
my_list = [1, 3, 20, 4, 1, 0]
list_length = len(my_list)
print("The list is:")
print(my_list)
print("The result is")
print(find_peak(my_list, list_length))
The list is: [1, 3, 20, 4, 1, 0] The result is 2
How It Works
The function checks three cases:
Single element: If the array has only one element, it's considered a peak
First element: If the first element is greater than or equal to the second, it's a peak
Last element: If the last element is greater than or equal to the second last, it's a peak
Middle elements: An element is a peak if it's greater than or equal to both neighbors
Alternative Implementation
Here's a simplified version that finds all peak elements ?
def find_all_peaks(numbers):
peaks = []
n = len(numbers)
for i in range(n):
is_peak = True
# Check left neighbor
if i > 0 and numbers[i] < numbers[i-1]:
is_peak = False
# Check right neighbor
if i < n-1 and numbers[i] < numbers[i+1]:
is_peak = False
if is_peak:
peaks.append(i)
return peaks
numbers = [1, 3, 20, 4, 1, 0]
peak_indices = find_all_peaks(numbers)
print("Numbers:", numbers)
print("Peak indices:", peak_indices)
print("Peak values:", [numbers[i] for i in peak_indices])
Numbers: [1, 3, 20, 4, 1, 0] Peak indices: [2] Peak values: [20]
Conclusion
Peak elements are useful in array analysis and can be found by comparing each element with its neighbors. The algorithm runs in O(n) time complexity and can return either the first peak or all peaks depending on requirements.
