Examples:
1)
v v
[1,0,0,1,1,1,1,0,1,1,0,0,0]
^ ^
would return a result of 10 as this is the minimum length of space between the first instance of a nonzero value and the last (bolded).
If we instead considered the following:
v v
[1,0,0,1,1,1,1,0,1,1,0,0,0]
^ ^
and looped to capture all the nonzero values, the length of space would be 13 so 10 is our answer.
2)
v v
[0,0,1,0,0,0,0,0,0,1,1]
^ ^
would return a result of 5 since looping is allowed. If we instead considered the following:
v v
[0,0,1,0,0,0,0,0,0,1,1]
^ ^
and did not loop, the length of space would be 9 so 5 is our answer.
CodePudding user response:
You can use np.sign np.argmax to the find the index of the first non-zero value, and np.cumsum np.argmax to find the index of the last non-zero value. Then subtract those:
>>> a = [1,0,0,1,1,1,1,0,1,1,0,0,0]
>>> np.cumsum(a).argmax() - np.sign(a).argmax() 1
9
np.signessentially reduces each value in the array to it's sign, so negative numbers become-1, positive numbers become1, and0stays0.np.argmaxreturns the 0-based index of the first occurence of the largest value in the array, which will be1due tonp.sign, so it will be the index of the first1, which works nicely for this case.np.cumsumperforms a cumulative sum accross all the items of the array. Because of this, the first occurence of the largest value in the array will be the last non-zero value, sonp.argmaxagain is perfect.
