I am trying to find the closest number to 5 in set b. This is my code.
JavaScript
x
8
1
b={1,2,45,65,3,2,8}
2
one=5
3
a=set()
4
for x in b:
5
c=abs(x-one)
6
a.add(c)
7
print(min(a))
8
Advertisement
Answer
You can use the key
argument to min
to achieve this:
JavaScript
1
4
1
b = {1,2,45,65,3,2,8}
2
target = 5
3
result = min(b, key=lambda x: abs(x - target))
4