+ 4
Pls help me. With the logic
data={-1,1,2} def analyze(data): myData= data or '0' ans = [int(d) for d in myData] ans.sort(key = lambda x:(abs(x) , -x)) print(ans[0]) analyze(data)
5 ответов
+ 5
data={-1,1,2}
#data is a set with unique elements (unordered)
myData= data or '0'
#perform the operation on "data" or on 0 if "data" isn't specified
ans = [int(d) for d in myData]
#list comprehension: turn set into a list (could have just used list() instead, the int() isn't needed)
ans.sort(key = lambda x:(abs(x) , -x))
#sort elements by their absolute value (that's why it needed to be converted into a list before, a set can't be sorted)
print(ans[0])
#print first element
(Sorry, I'm on my way to work ^^)
+ 3
The lambda function returns a tuple of two numbers, abs(x) and -x. For 1 it returns (1, -1), for -1 it returns (1, 1). These numbers are used to sort the list.
As long as the numbers in the list have different absolute values, only the first number of the tuple is used and the numbers are sorted by their absolute value in ascending order. As soon as they have the same absolute value like 1 and -1, the second value is used and they are sorted by their negative value. That's why 1 (negative value: -1) comes before -1 (negative value: 1).
+ 2
+ 2
thank u so much😁
+ 1
I don't understand the lamdba function. What does (abs(x), -x) do? The sorted list seems to contain [1, -1, 2] but I simply can't figure out how it works, I can't even find this syntax with Google.