I'm trying to find the closest number in a list to a certain variable, I have managed the first step,
def closest(lst, K):
return lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))]
lst = [1.25, 1.35, 2.12, 2.35, 2.45, 3.44, 4.01, 4.56, 4.85, 5.02, 5.56, 6.52,7.56]
K = 4.36
print(closest(lst,K)) #Output: 4.56
the second step however has been a challenge. i wanted now to be able not only to find the closest number, to a variable but also to make it more specific such that the closest number should also be less than the variable. The output for that function above is 4.56, I would however like to get an output of 4.01.
Any advice on how I can alter my code to come but that output?