Is there any method in python to find which of two values is closet a given number?
Say i have two values such as 1.5 and 5.5, and i want to find which of them is closest to 3. Not using Lists
Is there any method in python to find which of two values is closet a given number?
Say i have two values such as 1.5 and 5.5, and i want to find which of them is closest to 3. Not using Lists
You can use min
with a key function, the abs
of their respective difference to the compare key:
min((1.5, 3.5), key=lambda x: abs(3-x))
# 3.5
I don't know if there's a built-in function for doing this, but its so easy to do your self, for example:-
Edit:-
Sorry i made some simple wrongs first because of i am using a mobile phone and i cant compile it but i fixed them:-
def closer(n1, n2, main):
if(abs(main-n1)>abs(main-n2)):
return n2
else:
return n1
print(closer(1.5, 5.5, 3))
#the result is 1.5