ShellRox ShellRox - 1 year ago 73
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
is nearest value from all the value variables?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download