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

如何使用NumPy快速判断数组是否符合‘正数→负数→正数’的模式?

Answer

Absolutely! You can create a concise function using NumPy's vectorized operations to check this specific pattern. Here's how to do it:

import numpy as np

def foundPattern(arr):
    # Compute the sign of each element (1 for positive, -1 for negative, 0 for zero)
    signs = np.sign(arr)
    
    # If there are any zeros, the pattern is invalid (zeros aren't positive/negative)
    if (signs == 0).any():
        return False
    
    # Find indices where the sign changes between consecutive elements
    sign_changes = np.where(np.diff(signs) != 0)[0] + 1
    
    # Build the sequence of unique sign segments
    unique_signs = np.concatenate([[signs[0]], signs[sign_changes]])
    
    # Check if the sequence strictly follows positive → negative → positive
    return np.array_equal(unique_signs, np.array([1, -1, 1]))

How it works:

  1. Sign Calculation: np.sign() converts each element to 1 (positive), -1 (negative), or 0 (zero). We immediately return False if there are any zeros since they break the required positive/negative segments.
  2. Detect Sign Changes: np.diff() finds where consecutive elements have different signs. Adding 1 to the indices gives us the start of each new sign segment.
  3. Unique Sign Sequence: We construct the sequence of distinct sign segments by taking the first element's sign and then the sign at each change point.
  4. Pattern Check: Finally, we verify if this sequence matches exactly [1, -1, 1] (positive → negative → positive).

Test your examples:

myArray = np.array([5, 5, 3, 6, -2, -5, 4, 9])
print(foundPattern(myArray))  # Output: True

myArray2 = np.array([5, 5, 3, 6, 8, 4, -5, -8])
print(foundPattern(myArray2)) # Output: False

Edge Cases Handled:

  • Arrays with exactly three elements (e.g., [1, -1, 2] → returns True)
  • Arrays with extra sign changes (e.g., [1, -1, 2, -3] → returns False)
  • Arrays starting/ending with the wrong sign (e.g., [-1, 2, -3] → returns False)
  • Arrays containing zeros (e.g., [1, 0, -1] → returns False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 18:39:05