Skip to content
Advertisement

Find the nearest value to the given one in set

I am trying to find the closest number to 5 in set b. This is my code.

b={1,2,45,65,3,2,8}
one=5
a=set()
for x in b:
  c=abs(x-one)  
  a.add(c)
print(min(a))

Advertisement

Answer

You can use the key argument to min to achieve this:

b = {1,2,45,65,3,2,8}
target = 5 
result = min(b, key=lambda x: abs(x - target))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement