Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the immediate minimum among a list of numbers in python

How can I get the next minimum value to a value provided in python? Is there any inbuilt functions for it?

>>>num_list=[1,2,3,4]
>>> min(num_list)
1
>>> max(num_list)
4

How can I find the next lowest to 3 or next greatest to 2 ? The expected results are 2 and 3 respectievely.

like image 751
cutteeth Avatar asked Apr 06 '15 13:04

cutteeth


2 Answers

TL;DR Either min(n for n in my_list if n>lower_bound) or max(n for n in my_list if n<upper_bound)


A much faster alternative for finding the immediate minimum or the immediate maximum is numpy

>>> import numpy as np
>>> np.random.seed(10)
>>> a = np.random.random(10000)
>>> a[a>0.7].min()
0.69999533217645671
>>> a[a<0.7].max()
0.70003449227846715

If you are uncomfortable using the numpy machinery and want to deal simply with a list

>>> a = list(a)

then you can use the min and max builtins along with generator expressions

>>> min(n for n in a if n>0.7)
0.69999533217645671
>>> max(n for n in a if n<0.7)
0.70003449227846715
>>>

Using lists you have, of course, the same results but beware that there is a difference in performance: using ipython and %timeit to get the timings, I had 871 µs using numpy and 13.8 ms using regular lists for the 100000 elements array/list of the previous examples.

HTH, ciao


Post Scriptum

The solutions in my answer are all O(n), compared with the O(n log n) of methods that use sorting --- further, for large data sets the numpy approach should (italics because I have no testing at hand...) be affected by a small multiplicative factor.

like image 119
gboffi Avatar answered Sep 18 '22 15:09

gboffi


I see your question is tagged [lower-bound] and [upperbound]. If your list is sorted, Python has an equivalent of C++ <algorithm>'s lower_bound and upper_bound. They're in the bisect module. They return the indices of the begin and immediately after the end of a range of some specific value.

In [1]: import bisect

In [2]: A = [0, 1, 3, 3, 5]

In [3]: A[bisect.bisect_left(A, 3)-1]
Out[3]: 1

In [4]: A[bisect.bisect_right(A, 3)]
Out[4]: 5
like image 37
Juan Lopes Avatar answered Sep 19 '22 15:09

Juan Lopes