Answer the question
In order to leave comments, you need to log in
Explain what it means in sorted(values, key=lambda x: (abs(x-one), x)) the last value of x (after the decimal point)?
I'm from beginners))
There is a task:
You are given a list of values and a value to find the closest relative to.
For example, we have the following series of numbers: 4, 7, 10, 11, 12, 17. And we need to find the closest value to the number 9. If we sort this series in ascending order, then there will be 7 to the left of 9, and 10 to the right. But 10 - is closer than 7, so the correct answer is 10.
def nearest_value(values, one: int) -> int:
return sorted(values, key=lambda x: (abs(x-one)))[0]
print(nearest_value([4, 7, 10, 11, 12, 17], 9)) == 10
print(nearest_value([4, 7, 10, 11, 12, 17], 8)) == 7
print(nearest_value([0, -2}, -1)) == -2
def nearest_value(values, one: int) -> int:
return sorted(values, key=lambda x: (abs(x-one), x))[0]
Answer the question
In order to leave comments, you need to log in
Your function returns not one element, but all, sorted in order of removal from the given one.
This is a function by which the elements of an array are sorted.
The value of this function is a tuple of two elements: the first is the modulus of the difference, and the second is the current element of the list.
Tuples can be compared with > and <. They are compared element by element from left to right.
The point of adding x is that the distance from -1 to 0 and to -2 is the same and sorting did not distinguish these two elements from each other. When you began to sort by the key tuple, then if the distance is equal, the order is determined by the value of the element itself. The one that is smaller is selected first (in your case -2).
key=lambda x: (abs(x-one), x)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question