-4

I have a numpy array as follows:

import numpy as np
a = np.array([1, 4, 2, 6, 4, 4, 6, 2, 7, 6, 2, 8, 9, 3, 6, 3, 4, 4, 5, 8])

and a constant number b=6

I am searching for a number c which is defined by the number of times the elements in a are less than b 2 or more times consecutively.

So in this example it c=3

I have no working code, that's why I am asking that here. Based on a previous question I can use np.sum(a<b) to get the number of times that a<b.

print(np.sum(a<b))
#12

Now I want to count the number of times where a is two or more times consecutively less than b.

Here is an illustration of the 3 groups in for this sample a:

1, 4, 2, 6, 4, 4, 6, 2, 7, 6, 2, 8, 9, 3, 6, 3, 4, 4, 5, 8  # numbers in a
1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0  # (a<b)
^^^^^^^-----^^^^-----------------------------^^^^^^^^^^---  # (a<b) 2+ times consecutively
   1         2                                    3
pault
  • 41,343
  • 15
  • 107
  • 149
steve
  • 511
  • 1
  • 9
  • 33
  • it is maybe not clear but the condition is defined by the number of times that `a` is inferior to `b` at least 2 times consecutively so `c=3` – steve Jul 03 '19 at 16:58
  • 1
    For future reference: you'll get a more positive response in general if you share your attempt at solving the problem yourself, even if that attempt is inefficient or doesn't work. [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users). – pault Jul 03 '19 at 17:04

1 Answers1

2

You can use numpy masking and itertools.groupby.

from itertools import groupby

b = 6
sum(len(list(g))>=2 for i, g in groupby(a < b) if i)
#3
pault
  • 41,343
  • 15
  • 107
  • 149