0

Does numpy have an easy way to determine if an array has a pattern that looks like this: (positives numbers followed by negative numbers followed by positive numbers)?

Example:

myArray = np.array([5, 5, 3, 6, -2, -5, 4, 9])
myArray2 = np.array([5, 5, 3, 6, 8, 4, -5, -8])

if foundPatern(myArray):  # True
if foundPatern(myArray2): # False
1
  • 1
    A pure numpy solution: check = np.all((x[np.hstack((True,np.diff(x>=0)))]>=0)==[True,False,True]) where x is your array. I keep only the value where the sign change and check if the sign is indeed Positive Negative Positive. Commented Jun 9, 2021 at 14:48

1 Answer 1

1

There exists a numpy built-in to convert each element of an array to 1, 0, -1 based on the sign. You could easily use itertools.groupby for this task after converting the sign:

from itertools import groupby
import numpy as np


def foundPattern(lst):
    g = list(groupby(np.sign(lst)))
    return (len(g)==3 and g[0][0]==1.0)

This works as follows:

  1. The items of your array are grouped based on their sign (+ or -)
  2. If exactly 3 groups exist and the first one is a group of positives, you return True; in all other cases you return False

Note that you have not specified how edge cases are to be treated (e.g., 0 in the array) so I will not attempt to handle them in any way. Be mindful however that they do exist. Another example of an edge case could be NaN.

Sign up to request clarification or add additional context in comments.

4 Comments

This is perfect! Didn't know of itertools until now. Thanks for the detailed explanation! :)
@FarhanAhmad then you better have a look because itertools is an extremely useful library. Cheers.
There is a numpy built-in for this: np.sign. You can modify the first line of the function to: g = list(groupby(np.sign(lst)))
@SNygard thats even better! Feel free to edit, I am away from the pc atm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.