如何使用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:
- Sign Calculation:
np.sign()converts each element to 1 (positive), -1 (negative), or 0 (zero). We immediately returnFalseif there are any zeros since they break the required positive/negative segments. - 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. - 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.
- 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]→ returnsTrue) - Arrays with extra sign changes (e.g.,
[1, -1, 2, -3]→ returnsFalse) - Arrays starting/ending with the wrong sign (e.g.,
[-1, 2, -3]→ returnsFalse) - Arrays containing zeros (e.g.,
[1, 0, -1]→ returnsFalse)
内容的提问来源于stack exchange,提问作者Farhan Ahmad
相关产品推荐
相关产品推荐

