Find min value in array > 0

六月ゝ 毕业季﹏ 提交于 2019-12-03 05:26:07

You can use a generator expression with min. This will set m as the minimum value in a that is greater than 0. It then uses list.index to find the index of the first time this value appears.

a = [4, 8, 0, 1, 5]

m = min(i for i in a if i > 0)

print("Position:", a.index(m))
print("Value:", m)
# Position: 3
# Value: 1

You can use the min function and enumerate function, like this

result = min(enumerate(a), key=lambda x: x[1] if x[1] > 0 else float('inf'))
print("Position : {}, Value : {}".format(*result)
# Position : 3, Value : 1

This makes sure that, if the value is greater than 0, then use that value for the minimum value comparison otherwise use the maximum possible value (float('inf')).

Since we iterate along with the actual index of the items, we don't have to find the actual index with another loop.

Here is another way of doing it with a generator expression. Note how the values coming from enumerate (a and b) are swapped in the tuple to sort correctly.

value,position = min(((b,a) for a,b in enumerate(myArray) if b>0), default=(None,None))

The default argument will be returned when the generator expression returns nothing (i.e. there are no items greater than 0). The default can be set to whatever makes sense in the surrounding program logic - here returning None will allow you to test with either if value: or if position:

def find_min_position(array):
    plus_array = [elem for elem in array if elem > 0]
    min_elem = min(plus_array)
    return min_elem, array.index(min_elem)

In : find_min_position([4, 8, 0, 1, 5])
Out: (1, 3)

add a filter then :

myArray = [4, 8, 0, 1, 5]
result = min(filter(lambda x: x > 0, myArray))
print result # 1
print myArray.index(result) # 3
import numpy as np

x = np.array([1,2,0,5,10])
x = np.extract(x>0,x)
min_index = np.amin(x)
min_value = np.argmin(x)

the complicated / algorithmic way:

int min = array[0], i = 1
list smallest //list of indexes of the smallest element 

// find the first element greater than 0
while (min <= 0 and i < array.length) {
    min = array[i]
    i++
}

// find the first instance of the smallest element greater than 0
while (i < array.length) {
    if (array[i] < min and array[i] > 0) {
        clear the list
        min = array[i]
        list.append(i)
    }
    else if (array[i] == min) {
        list.append(i)
    }
    i++;
}

the first instance of the smallest element greater than 0 is now the first element that you added to the list.

edit: you'll also have a list of every index of the smallest value. Some simple checks can tell you if there are no elements in the array greater than 0, or if the list is empty, etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!