Given an array consisting of non-negative numbers, I want to be able to find the index of the middle 0 for each of the consecutive 0's in the array, excluding 0's that are found at the start or the end of the array. A simple example: we have given array
np.array([0, 0, 0, 1, 2, 0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 5, 6, 0, 0, 0])
Then, I want to return indices 6 and 13 (for an even amount of consecutive 0's, I want either the floor or ceil).
Now, my current implementation is as follows:
def middle_zero(array):
busy = False
not_start_zero = False
middle_zero_list = []
for i in range(len(array)):
if array[i] > 0:
not_start_zero = True
if array[i] == 0 and not_start_zero and not busy:
start = i
busy = True
if busy and array[i] > 0:
end = i
middle_zero_list.append(int(np.mean([start, end])))
busy = False
return np.array(middle_zero_list)
middle_zero(np.array([0, 0, 0, 1, 2, 0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 5, 6, 0, 0, 0]))
>> array([6, 13])
Although it is working, I think that a much more clever solution is possible here. As I have to do this computation many times, I want it to be more efficient.
numba.njit. Have you tried that?middle_zero(np.array([0, 1, 2, 0, 0, 0, -3, -2, 0, 0, 0, 0, 0, 0, 5, 6, 0, 0]))givesarray([8])so it's not the middle of zeros, it's the middle of non positives