# [SciPy-user] indices of consecutive elements

alex argriffi@ncsu....
Tue Dec 2 13:38:07 CST 2008

```Here's a way that uses ufuncs.

from numpy import *
v = [0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0]
myufunc = frompyfunc(lambda a, b: (a+b)*b, 2, 1)
where(diff(myufunc.accumulate(v)) <= -4)

This gives (array([5,18]),) where 5 and 18 are the right hand indices;
the left hand indices can be found similarly.

Alex

Daniel Ashbrook wrote:
> I'm trying to figure out a way to return the indices of the start and
> end of a run of consecutive elements that match some condition, but only
> if there are more than a certain number.
>
> For example, take the array (with indices in comment for clarity):
>
> #0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20 21 22
> [0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0]
>
> I want to find the start and end indices of all runs of 1s with length
> of 4 or longer; so here the answer would be:
>
> [[2,5], [15,18]]
>
> Is there a reasonable way to do this without looping? I've been playing
> around with diff() and where() but without too much progress.
>
> Thanks,
>
>
> dan
> _______________________________________________
> SciPy-user mailing list
> SciPy-user@scipy.org
> http://projects.scipy.org/mailman/listinfo/scipy-user
>

```