I wanted to know if there is a way to find the smallest number in the list which is closest to a given number.
Foe e.x.
my_list=[1,10,15,20,45,56]
my_no=9
Output should be equal to 1 Explanation: since 9 comes between 1 and 10 and I want the smaller number, i.e. 1.
Similarly if my_no=3, output is equal to 1
I am new to python, so any help will be much appreciated. Thanks!
CodePudding user response:
I've used bisect to do this:
from bisect import bisect_right
my_list=[1,10,15,20,45,56]
my_no=9
targ=bisect_right(my_list, my_number)
#edge case where you give a number lesser than the smallest number in the list. e.g. my_no=0 in your case
if(targ):
print(my_list[targ-1])
Output=1
CodePudding user response:
You can reduce
from functools
:
from functools import reduce
i = reduce(lambda l, r: l if l <= my_no <= r else r, my_list)
print(i)
# Output
1
Test
# my_no = 18
>>> reduce(lambda l, r: l if l <= my_no <= r else r, my_list)
15
# my_no = 59
>>> reduce(lambda l, r: l if l <= my_no <= r else r, my_list)
56
Note: this code doesn't work if my_no < my_list[0]
. You have to check it before.
CodePudding user response:
If you want to stick to basics and want to approach it using for loop
and if statement
then it can be achieved as follows:
my_list=[1,10,15,20,45,56]
given_number = 9
output=my_list[0]
for x in my_list:
if(x < given_number and x > output):
output= x
print(output)
# Output
1
CodePudding user response:
List comprehension is another elegant way to do this.
my_list=[1,10,15,20,45,56]
my_no = 9
output = max([x for x in my_list if x<=my_no])
print(output) #1