I would like to get the following output with two functions :
>>> myList = [25, 35, 57, 61, 79]
>>> myNumber = 38
>>> take_closest_high(myList, myNumber)
...
57
>>> take_closest_low(myList, myNumber)
35
...
The list is not necessarily ordered.
Thank you !
I have seen from another topic this solution
min(myList, key=lambda x:abs(x-myNumber))
that returns the closest number of the list
EDIT : I made it work with the following. Thanks !
min(myList, key=lambda x:abs(x-38) if x-38>0 else x)
Out[8]: 57
min(myList, key=lambda x:abs(x-38) if x-38<0 else x)
Out[9]: 35
CodePudding user response:
To get the closest high, filter myList
such that all of its elements are greater than myNumber
, and return the smallest value.
def take_closest_high(myList, myNumber) :
filteredHigh = list(filter(lambda x : x>myNumber, myList))
if filteredHigh==[] :
return None
return min(filteredHigh)
To get the closest low, filter myList
such that all of its elements are lower than myNumber
, and return the greatest value.
def take_closest_low(myList, myNumber) :
filteredLow = list(filter(lambda x : x<myNumber, myList))
if filteredLow==[] :
return None
return max(filteredLow)
CodePudding user response:
Using min & max with default on generators. Default provides value for empty lists.
Code
def take_closest_high(myList, myNumber):
# Min over numbers in list >= myNumber
return min((x for x in myList if x >= myNumber), default = None)
def take_closest_low(myList, myNumber):
# Max over numbers in list <= myNumber
return max((x for x in myList if x <= myNumber), default = None)