2

Here is the code:

import numpy as np
array = np.array([15, 55, 9, 99, 8, 21, 2, 90, 88])

this will output an array([ 15, 55, 9, 99, 8, 21, 2, 90, 88]).

How can I find the first minimum number without sorting then the second minimum number?

I expect the output to be: first min = 9 second min = 8

2 Answers 2

2

You can find the absolute minimum like this:

In [35]: import numpy as np

In [36]: arr = np.array([15, 55, 9, 99, 8, 21, 2, 90, 88])

In [37]: first = np.min(arr)

In [38]: second = np.min(arr[arr != first])

In [39]: first
Out[39]: 2

In [40]: second
Out[40]: 8

To obtain the indices of the local minima, you could use scipy.signal.argrelmin:

In [52]: from scipy.signal import argrelmin

In [53]: idx = argrelmin(arr)[0]

In [54]: idx
Out[54]: array([2, 4, 6], dtype=int64)

In [55]: arr[idx]
Out[55]: array([9, 8, 2])
Sign up to request clarification or add additional context in comments.

4 Comments

no the first min is 9, the second min is 8 the third min is 2
Then you meant "local" minimum
Yes, how I find local minimum without sorting?
Sorting will not help anyway. Imagine [ 90 80 5 4 67 55 80] . Sorting will give you 5 and 4 while I guess you expect 4 and 55. Just use change of "derivative" sign. Loop over the list and compute difference of the element with the previous. If negative, continue the loop, if positive and previous negative, than previous is a local minimum. Proceed then with positive differences until a negative one will trigger a second "descent", then the next hit will be a positive difference.
1

You could offset the list and zip them:

l0 = [15, 55, 9, 99, 8, 21, 2, 90, 88]
l1 = l0[1:]
l2 = [-1] + l0

[x for x,y,z in zip(l0,l1,l2) if (x < y) & (x < z)]
# Out[32]: [9, 8, 2]

or in one line:

l = [15, 55, 9, 99, 8, 21, 2, 90, 88]
[x for x,y,z in zip(l,l[1:],[-1]+l) if (x < y) & (x < z)]
# Out[32]: [9, 8, 2]

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.