-5

I am looking to identify the smallest value greater than 0 from a list but need some help.

Can anyone provide some example code?

Thanks

Lucas
  • 3,376
  • 6
  • 31
  • 46

3 Answers3

4

Given initial list called values:

values = [...]
result = min(value for value in values if value > 0)

The resulting value is stored in result. Here we use generator expression with filtering instead of list comprehensions for memory savings O(1) memory in this case.

Community
  • 1
  • 1
sasha.sochka
  • 14,395
  • 10
  • 44
  • 68
3
def smallest_value_greater_than_0(numbers):
    return min(num for num in numbers if num > 0)

As requested in your comment, if you have a dictionary and want to return both the key and value of the item with the smallest value:

def smallest_value_greater_than_0(numbers):
    value, key = min((v, k) for k, v in numbers.iteritems() if v > 0)
    return key, value

numbs = dict(A=2, B=3, C=0)
key, value = smallest_value_greater_than_0(numbs)     # key="A", value=2

(In Python 3.x, just use numbers.items() instead of numbers.iteritems(). Also note in Python 3 that all the keys should be of the same type.)

Note that if multiple entries have the same value, this will return the one with the lowest key, using Python's sorting order. For example, if A=1, B=3, C=0, D=1, you will get A=1 back, never D=1. If some keys are numbers and others are strings, or some are uppercase and some are lowercase, you may not get the result you expect, though it will be predictable.

kindall
  • 178,883
  • 35
  • 278
  • 309
0

You can use a generator:

def smallestPositive(lst):
    return min(x for x in lst if x > 0)
jh314
  • 27,144
  • 16
  • 62
  • 82