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
Program to find indices or local peaks in Python
A local peak is an element that is greater than or equal to its neighbors. In Python, we can find indices of local peaks by comparing each element with its adjacent elements. A peak can be a single element or a plateau (consecutive equal elements that are peaks).
Peak Definition
An index i is a peak when these conditions are met:
- The next different number is either absent or smaller than nums[i]
- The previous different number is either absent or smaller than nums[i]
- There is at least one different number on either side
Algorithm Steps
The algorithm processes consecutive equal elements as groups:
- Iterate through the array with index i
- For each position, find the end of the current plateau
- Check if this plateau is a peak by comparing with neighbors
- If it's a peak, add all indices in the plateau to the result
Example
Let's implement the solution to find local peak indices:
def solve(nums):
n = len(nums)
ans = []
i = 0
while i < n:
i0 = i
# Find the end of current plateau
while i < n and nums[i] == nums[i0]:
i += 1
# Check if this plateau is a peak
left_smaller = (i0 == 0 or nums[i0] > nums[i0 - 1])
right_smaller = (i == n or nums[i0] > nums[i])
if left_smaller and right_smaller:
# Ensure it's not the entire array
if i0 != 0 or i != n:
ans.extend(range(i0, i))
return ans
# Test with example
nums = [5, 8, 8, 8, 6, 11, 11]
result = solve(nums)
print("Input:", nums)
print("Peak indices:", result)
Input: [5, 8, 8, 8, 6, 11, 11] Peak indices: [1, 2, 3, 5, 6]
How It Works
For the input [5, 8, 8, 8, 6, 11, 11]:
- Index 0 (value 5): Not a peak since 8 > 5 on the right
- Indices 1-3 (values 8, 8, 8): Peak plateau since 8 > 5 and 8 > 6
- Index 4 (value 6): Not a peak since 11 > 6 on the right
- Indices 5-6 (values 11, 11): Peak plateau since 11 > 6 and no right neighbor
Alternative Approach Using SciPy
For scientific applications, you can use SciPy's find_peaks function:
from scipy.signal import find_peaks
import numpy as np
def find_local_peaks_scipy(nums):
peaks, _ = find_peaks(nums)
return peaks.tolist()
# Test with example
nums = [5, 8, 8, 8, 6, 11, 11]
peaks = find_local_peaks_scipy(nums)
print("SciPy peaks:", peaks)
SciPy peaks: [1, 5]
Comparison
| Method | Handles Plateaus | Dependencies | Best For |
|---|---|---|---|
| Custom Algorithm | Yes (all indices) | None | Complete plateau detection |
| SciPy find_peaks | Partial (first index only) | SciPy | Scientific computing |
Conclusion
The custom algorithm handles plateaus by returning all indices in a peak region, while SciPy's find_peaks returns only the first index of each peak. Choose the custom approach when you need all plateau indices, or SciPy for standard peak detection in scientific applications.
