Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm (Python): find the smallest number greater than k

I have a question from algorithm point of view. I have a list of numbers (floats)

1.22,3.2, 4.9,12.3.....and so on

And I want to find the smallest number greater than (lets say) 4.. So the answer is 4.9 But besides the obvious solution.. (iterating thru list and keeping a track of smallest number greater than k) what is the "pythonic way" to do this. Thanks

like image 607
frazman Avatar asked Nov 12 '11 00:11

frazman


People also ask

How do you find the smallest number in Python?

Use Python's min() and max() to find smallest and largest values in your data. Call min() and max() with a single iterable or with any number of regular arguments.

How do you find the smallest number in a list in Python without Max?

Process: Initially assign the element located at 0 to min using min = l[0]. using for loop visit each location serially from 1 to len(l)-1. if the element located in any position is lesser than min, then assign the element as min by using min = l[i] finally min holds the minimum value in the list.


1 Answers

min(x for x in my_list if x > 4)
like image 121
Sven Marnach Avatar answered Sep 19 '22 13:09

Sven Marnach