I like to present 3 functions doing similar approximation but using lists:
def closest(lst, K):
return lst[min(range(len(lst)), key=lambda i: abs(lst[i]-K))]
In order to understand the upper function, this next function is similar:
def closest(lst, K):
minim = None
for i in lst:
aux = abs(i - K)
if minim is None:
minim = aux
result = i
if aux < minim:
minim = aux
result = i
return result
Using numpy library:
import numpy
def closest(lst, K):
lst = numpy.asarray(lst)
idx = (numpy.abs(lst - K)).argmin()
return lst[idx]
You can call the upper functions using example like this:
lst = [2.4, 3.2, 6.9, 7.2, 9.8]
K = 5.1
print(closest(lst, K))
Note: if the number is just in the middle, then the function get the minimum value.
abs(num1 - num2) <= 1is_adjacent(num1, num2)and then call that function. Then, if you use the verbose code you started with, it's only verbose in one place; if you're not sure you understand the smarter code by Johnny Mopp, it's isolated to a single place you can test separately; if you want to change it later, there's only a single place to change it; etc.any(num1==x for x in range(num2-1, num2+1)), but they might come up with the expanded-out version of that. (And maybe the no-loop thing isn't supposed to be a restriction to ban that answer, but a hint to make them not go down the path of thinking that way?)