Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the closest elements above and below a given number

Tags:

python

numpy

myArr = array([4,1,88,44,3])
myNumber = 25
FindClosest(myArr, myNumber)
...
4, 44

Is there any way to find the closest 2 numbers in a list to a given number such that one of them is higher and the other lower?

I can find the closest number by:

min(myArr.tolist(), key=lambda x:abs(x-myNumber))
like image 474
user308827 Avatar asked Mar 29 '16 04:03

user308827


People also ask

How do you find the closest element in a list?

We can find the nearest value in the list by using the min() function. Define a function that calculates the difference between a value in the list and the given value and returns the absolute value of the result. Then call the min() function which returns the closest value to the given value.

How do you find the nearest number in Python?

Python round() Function The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.

How do I find the nearest number in an array?

So if the array is like [2, 5, 6, 7, 8, 8, 9] and the target number is 4, then closest element is 5. We can solve this by traversing through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolute difference.

How do you check if a number is closer to another number in Python?

The math. isclose() method checks whether two values are close to each other, or not. Returns True if the values are close, otherwise False. This method uses a relative or absolute tolerance, to see if the values are close.


2 Answers

Sorting is not necessary, and makes this time complexity O(n logn) when it should be just O(n).

I believe this is what you're looking for, taking advantage of numpy array indexing:

>>> # the smallest element of myArr greater than myNumber
>>> myArr[myArr > myNumber].min()  
44

>>> # the largest element of myArr less than myNumber
>>> myArr[myArr < myNumber].max()
4
like image 187
wim Avatar answered Sep 29 '22 20:09

wim


upper = min([ i for i in myArr.tolist() if i >= myNumber], key=lambda x:abs(x-myNumber))
lower = min([ i for i in myArr.tolist() if i < myNumber], key=lambda x:abs(x-myNumber))
like image 20
kjschiroo Avatar answered Sep 29 '22 20:09

kjschiroo