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))
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.
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.
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.
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.
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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With