Write a program that finds the closest element in an array to a given number.
Input data
The first line contains a list of numbers – the elements of the array (integers not exceeding 1000 in absolute value).
The second line contains one integer x not exceeding 1000 in absolute value.
Output
Print the value of the array element closest to x. If there are several such numbers, print any of them.
Examples
Input 1 2 3 4 5
6
Conclusion 5
Example of my code:
import sys
a = list (map (int, input (). split ()))
b = int (input ())
c = []
for i in a:
c.append (b-i)
for i in a:
if i == b:
print (b)
sys.exit ()
if min (c) & lt; 0:
d = c.index (max (c))
print (a [d])
else:
d = c.index (min (c))
print (a [d])
Writes in the test that the code gives an incorrect answer
Answer 1, authority 100%
Here’s the code:
import sys
a = list (map (int, input (). split ()))
b = int (input ())
c = []
for i in a:
c.append (abs (b-i))
d = c.index (min (c))
print (a [d])
abs – takes the value modulo
Answer 2, authority 33%
I can suggest this solution:
Algorithm:
- Sort a list of numbers
- I iterate through the list and find the first superior number to the given
b
. - I find the neighbors of the number
b
, based on the largest number from point 2, and compare them for closeness to a given number. - I display the first number or the maximum in the list
Implementation:
a = sorted (list (map (int, input (). split ())))
b = int (input ())
res = []
for num, i in enumerate (a):
if i & gt; = b:
if b - a [num - 1] & gt; a [num] - b:
res.append (a [num])
else:
res.append (a [num - 1])
if res:
print (res [0])
else:
print (max (a))
Answer 3, authority 33%
The min
built-in function has an optional key
argument that accepts a function that determines the order in which elements are compared:
a = [1,2,3,4,5,7,6,15]
b = 19
m = min (a, key = lambda x: abs (x-b)) # 15
Here x
elements are compared to each other by the absolute difference between them and the specified b
value. That is, the smaller will be the one with the smaller difference.