Find the closest elements above and below a given number

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

above = min([i for i in myArr if myNumber < i])
below = max([i for i in myArr if myNumber > i])

Also, the correct answer is 44, 4 not 44, 88


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))

Tags:

Python

Numpy