Issue
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))
Solution
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
Answered By - wim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.