0

I am trying to take an array of integers such as:

[1,2,3,4,9,10,11,12,18,19,20,21] and get the values at which there is a "jump," so, the output of my program would be [1,9,18]. I wrote the following code in Python which seems to be taking forever to run:

min_indices = np.where(data[:,1] == data[:,1].min())
start_indices = np.array([0])
i = 1
while (i < len(min_indices[0])):
    if (min_indices[0][i] != (min_indices[0][i-1] + 1)):
        start_indices.append(min_indices[i])
print start_indices
1
  • 2
    You never increment i in your loop, this is causing running forever. Commented Nov 17, 2014 at 16:43

3 Answers 3

3

Using list comprehension:

>>> a=[1,2,3,4,9,10,11,12,18,19,20,21]
>>> [a[i] for i,_ in enumerate(a[1:]) if (a[i]!=a[i-1]+1)]
[1, 9, 18]

and using zip:

>>> [a[0]]+[i for (i,j) in zip(a[1:],(a[:-1])) if (i!=j+1)]
[1, 9, 18]
Sign up to request clarification or add additional context in comments.

Comments

3

You are not incrementing "i" that I can tell.

1 Comment

Thanks. Forgot about that.
3

You can use numpy.diff with numpy.where here:

>>> a = np.array([1,2,3,4,9,10,11,12,18,19,20,21])
>>> indices = np.where(np.diff(a) > 1)[0] + 1
>>> np.concatenate(([a[0]], a[indices]))
array([ 1,  9, 18])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.