ShellRox ShellRox - 6 months ago 12
Python Question

Python: Finding nearest integer value to specific integer

I'm trying to add algorithm to my script that would find the nearest integer value from few variables, so for example:

int = 700
value1 = 400
value2 = 500
value6 = 600


How can i make script get that
value6
is nearest value from all the value variables?

Answer

Use min with an appropriate key function, e.g. the abs of the difference to i (which you really shouldn't name int):

i = 700  # don't shadow built-in name int
values = (value1, value2, ...)  # consider using a list/tuple from the beginning
nearest = min(values, key=lambda v: abs(i-v))

> nearest
600