Using NumPy:
import numpy as np seq = np.array([1,0,0,1,0,1,0,0,0,0,1,0]) arr = np.arange(len(seq)) result = arr - np.maximum.accumulate(arr * seq) print(result)
gives
[0 1 2 0 1 0 1 2 3 4 0 1]
Why is arr - np.maximum.accumulate(arr * seq) ? The desired result seemed to be related to a simple progression of integers:
arr = np.arange(len(seq))
So, the natural question is: if seq = np.array([1, 0, 0, 1, 0, 1]) and the expected result is expected = np.array([0, 1, 2, 0, 1, 0]) , then what value does x do
arr + x = expected
WITH
In [220]: expected - arr Out[220]: array([ 0, 0, 0, -3, -3, -5])
it looks like x should be the cumulative maximum of arr * seq :
In [234]: arr * seq Out[234]: array([0, 0, 0, 3, 0, 5]) In [235]: np.maximum.accumulate(arr * seq) Out[235]: array([0, 0, 0, 3, 3, 5])