numpy.diff is useful in this case. You can count the number -1 in the diff ed array.
Note that you also need to check the last element - if it is True, it will not have -1 in the diff ed array to indicate this. Even better, you can add False to the array before diff ing.
import numpy as np a = np.array([False, False, False, True, True, True, False, False, False], dtype=bool) d = np.diff(np.asarray(a, dtype=int)) d => array([ 0, 0, 1, 0, 0, -1, 0, 0]) (d < 0).sum() => 1
To add False to the end:
b = np.append(a, [ False ]) d = np.diff(np.asarray(b, dtype=int)) ...
Now the "sequence ..., True, False, ..., True ... never happens" iff (d<0).sum() < 2 .
The trick to avoid the append operation (and make your code more obscure) is: (d<0).sum() + a[-1] < 2 (that is, if [-1] is True, read it like a block). This will only work if a is not empty.
shx2
source share