You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻找两个局部极小值:求适用于任意t值列表的通用代码

Robust Local Minima Detection for Any List Length

Your original code hits index out-of-bounds issues when checking elements at the start/end of your t list, and fails to account for minima that sit exactly at the first or last position. Let's fix this with a robust solution that works for any length of t, and reliably finds up to two local minima.

Solution 1: Pure Python (Universal Compatibility)

This approach works for any Python iterable (lists, tuples, etc.) and explicitly handles edge cases:

def find_two_local_mins(t):
    t_min = []
    n = len(t)
    
    # Handle the first element
    if n >= 1:
        if n == 1:
            # Single element is the only minimum
            t_min.append(t[0])
        else:
            if t[0] < t[1]:
                t_min.append(t[0])
    
    # Handle middle elements (avoid index errors)
    for i in range(1, n - 1):
        if t[i] < t[i-1] and t[i] < t[i+1]:
            t_min.append(t[i])
    
    # Handle the last element
    if n >= 2:
        if t[-1] < t[-2]:
            t_min.append(t[-1])
    
    # Return up to two minima (take first two, or all if fewer exist)
    return t_min[:2]

# Example usage
t = [5, 3, 4, 2, 6, 1]
print(find_two_local_mins(t))  # Output: [3, 2]

Key Details:

  • We first calculate n = len(t) to avoid redundant length checks
  • The first element is checked against the second (if it exists) to see if it's a minimum
  • Middle elements are iterated from index 1 to n-2—this ensures we never try to access t[-1] or t[n] (which would throw errors)
  • The last element is checked against the second-to-last element
  • We return the first two minima found; if there are fewer than two, we return all available minima

Solution 2: NumPy + SciPy (Efficient for Large Datasets)

If you're working with large numerical arrays, using NumPy and SciPy's signal processing tools is faster and more concise:

import numpy as np
from scipy.signal import argrelextrema

def find_two_local_mins_np(t):
    t_np = np.asarray(t)
    n = len(t_np)
    min_indices = []
    
    # Find local minima in the middle of the array
    middle_mins = argrelextrema(t_np, np.less)[0]
    min_indices.extend(middle_mins)
    
    # Check edge cases (first/last elements)
    if n >= 1:
        if n == 1:
            min_indices.append(0)
        else:
            if t_np[0] < t_np[1]:
                min_indices.append(0)
            if t_np[-1] < t_np[-2]:
                min_indices.append(n-1)
    
    # Remove duplicate indices (in case edges were already detected as middle minima)
    unique_min_indices = np.unique(min_indices)
    # Get the corresponding values and return up to two
    return t_np[unique_min_indices][:2].tolist()

# Example usage
t = [10, 8, 9, 5, 7, 3, 4]
print(find_two_local_mins_np(t))  # Output: [8, 5]

Key Details:

  • argrelextrema efficiently finds indices of local minima in the middle of the array
  • We explicitly add indices for edge-case minima if they qualify
  • np.unique ensures we don't have duplicate entries (though edge indices won't overlap with middle minima from argrelextrema)
  • The result is converted back to a Python list for consistency

Optional: Sort Minima by Value

If you want the two smallest local minima (not just the first two encountered), modify the return line to:

return sorted(t_min)[:2]  # For pure Python version

Or for the NumPy version:

sorted_mins = np.sort(t_np[unique_min_indices])[:2]
return sorted_mins.tolist()

内容的提问来源于stack exchange,提问作者doctorwho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:42:04