Home python Why is the code not correct? Python

# Why is the code not correct? Python

Author

Date

Category

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

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

I can suggest this solution:

Algorithm:

1. Sort a list of numbers
2. I iterate through the list and find the first superior number to the given `b `.
3. 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.
4. 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))
``````

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.

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.