a = [13.6, 13.0, 12.1, 11.3, 10.3, 9.0, 8.8, 8.1] #list
value = 11.5 #value to find
min(range(len(a)), key=lambda i: abs(a[i]- value)) #just index
#result: 3
min(enumerate(a), key=lambda x: abs(x[1]-value)) #index and value
#result: (3, 11.3)
def closest(arr, target):
#1: calculate the delta between the number and the target for each numer (this is done in the list comprehension)
#2: enumerate them to get the index of the minimum
#2.1: key=... is used because now we have a tuple (check enumerate docs) so, knowing that x[0] is the index, we chose x[1], which is the actual value
#3 once we have the index use it to access the correct value in the original array
return arr[min(enumerate([abs(target-x) for x in arr]), key=lambda x: x[1])[0]]
def closest_with_bias(arr, target):
# this time we will do the same thing but we will have a bias towards numbers above or below the target
# for example if target is 0 then we can favor positive or negative numbers based on the POSITIVE_BIAS value
# differences:
# in the key function we add POSITIVE_BIAS to the calculated delta after checking if x is greater or equal than the target
# example:
# arr = [-4, 4, 5]
# target = 0
# calculated delta array = [4.1, 4, 5]
# min will then find the 4 which has index 1
# we have now favored 4 instead of -4
POSITIVE_BIAS = .1
bias = lambda x: abs(target-x[1]) if x[1]>=target else abs(target-x[1])+POSITIVE_BIAS
return arr[min(enumerate([bias(x) for x in arr]), key=bias)[0]]
def closest(lst, K):
return lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))]
# Driver code
lst = [3.64, 5.2, 9.42, 9.35, 8.5, 8]
K = 9.1
print(closest(lst, K))
min(range(len(a)), key=lambda i: abs(a[i]-11.5))
min(range(len(a)), key=lambda i: abs(a[i]-11.5))