Here's a vectorized solution with help from convolution -
def first_consecutive_negative_island(a, N=3):
mask = np.convolve(np.less(a,0),np.ones(N,dtype=int))>=N
if mask.any():
return mask.argmax() - N + 1
else:
return None
Sample run -
In [168]: a = [1,-1,1,-1,1,-1,1,-1,-1,-1,1,-1,1]
In [169]: first_consecutive_negative_island(a, N=3)
Out[169]: 7
Works irrespective of where the group exists -
In [175]: a
Out[175]: [-1, -1, -1, 1, -1, 1, -1, -1, -1, 1, -1, 1]
In [176]: first_consecutive_negative_island(a, N=3)
Out[176]: 0
With no negative numbers, it gracefully returns None
-
In [183]: a
Out[183]: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
In [184]: first_consecutive_negative_island(a, N=3)
For exactly three consecutive negative numbers search, we can use slicing, like so -
def first_consecutive_negative_island_v2(a):
m = np.less(a,0)
mask = m[:-2] & m[1:-1] & m[2:]
if mask.any():
return mask.argmax()
else:
return None
Timings -
In [270]: a = np.random.randint(-1,2,(1000000)).tolist()
In [271]: %timeit first_consecutive_negative_island(a, N=3)
10 loops, best of 3: 44.5 ms per loop
In [272]: %timeit first_consecutive_negative_island_v2(a)
10 loops, best of 3: 38.7 ms per loop