2
r = Counter(nums)
        
return sorted(nums, key=lambda x: (r[x], -x))

I wonder how the -x works in this sorted array.

How does this function get translated into which logics?

0

2 Answers 2

3

In this call to sorted:

r = Counter(nums)
sorted(nums, key=lambda x: (r[x], -x))

The lambda argument is just a function that gets called on elements of nums, returning the sort key to be used for that element. The keys are then compared to determine which element should come before the other.

In this case, for an element x in nums, it's constructing a key (r[x], -x). So the primary sort key is the value of r indexed by x. If those values are equal, then it breaks the tie by comparing -x, i.e. the negated values of x. The negation simply causes the comparison to be reversed, so larger values of x come before smaller values of x rather than the other way around.

Sign up to request clarification or add additional context in comments.

Comments

1

By defining key argument to .sorted() function, you change the way python normally sorts the elements of that iterator. By default you can think of it as : key = lambda x: x which means items themselves (no changes).

Here is an example:

lst = ['aa', 'bb', 'aaa', 'bbb', 'a', 'b']
print(sorted(lst, key=lambda x: x[0]))

output : ['aa', 'aaa', 'a', 'bb', 'bbb', 'b']

As you can see python sorts alphabetically by the "first" character of every item.

When you define a "tuple" let's say (x, len(x)), every single items in the list will convert to a tuple, so you're actually comparing a tuple with other tuples !

print((10, 40) < (10, 30))   # False

How do tuples compared with each other ? at first, x[0] with y[0] if the were equal then x[1] with y[1] and so on... So basically we defined priority with tuples.

lst = ['aa', 'bb', 'aaa', 'bbb', 'a', 'b']
print(sorted(lst, key=lambda x: (x[0], len(x))))

output : ['a', 'aa', 'aaa', 'b', 'bb', 'bbb']

It makes sense now, for first item in the list which is 'aa' the created tuple is ('a' , 2), second one is ('b', 2) etc. So these tuples are compared just like said before.

You don't have to use tuple, lists can be used as well. The comparison algorithm is the same as tuple:

lst = ['aa', 'bb', 'aaa', 'bbb', 'a', 'b']
print(sorted(lst, key=lambda x: [x[0], len(x)]))

output : ['a', 'aa', 'aaa', 'b', 'bb', 'bbb']

You now know what - minus does to your second item of the created tuple.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.