D
D
dmitriykyc2020-04-23 15:23:00
Python
dmitriykyc, 2020-04-23 15:23:00

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.


I solved it this way:

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


But, if we are looking in these values: my function returns 0, although it should return -2. Found this solution:
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]


But I do not understand what the last "x" does, which is after the comma?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Pankov, 2020-04-23
@dmitriykyc

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 question

Ask a Question

731 491 924 answers to any question