Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find min value in array > 0

Tags:

I am looking to find the lowest positive value in an array and its position in the list. If a value within the list is duplicated, only the FIRST instance is of interest. This is what I have which does what I want but includes 0.

print "Position:", myArray.index(min(myArray))
print "Value:", min(myArray)

for example, as it stands if,

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

then Position: 2, Value: 0

I want it to present position: 3, value: 1

like image 948
user3001499 Avatar asked Jan 15 '15 15:01

user3001499


People also ask

How do you find the minimum value of an array?

M = min( A ) returns the minimum elements of an array. If A is a vector, then min(A) returns the minimum of A . If A is a matrix, then min(A) is a row vector containing the minimum value of each column of A .

What does MIN () for a list return?

The min() function returns the item with the lowest value, or the item with the lowest value in an iterable.

How do you find the minimum value of an index?

Python's inbuilt function allows us to find it in one line, we can find the minimum in the list using the min() function and then use the index() function to find out the index of that minimum element.

How do you find the minimum positive value in Python?

Try this index_of_small = lst. index(min(filter(lambda x : x > 0, lst))) . Filter before finding min. Save this answer.


1 Answers

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
like image 98
Ffisegydd Avatar answered Sep 21 '22 17:09

Ffisegydd