Aaron Wei
Aaron Wei

Reputation: 85

Why does overriding __lt__ also change the greater-than operation? Why use it to sort?

I am doing leetcode (https://leetcode.com/problems/largest-number/) and I found the solution in leetcode is :

class LargerNumKey(str):
    def __lt__(x, y):
        return x+y > y+x

class Solution:    
    def largestNumber(self, nums: List[int]) -> str:
        largest_num = ''.join(sorted(map(str, nums), key=LargerNumKey))
        return '0' if largest_num[0] == '0' else largest_num

I am not sure about why here it overrides __lt__ in LargerNumKey. Why not override __gt__? And why does the condition in __lt__ use x+y > y+x?

Upvotes: 0

Views: 148

Answers (1)

Daweo
Daweo

Reputation: 36680

I am not sure about why here it overrides __lt__ in LargerNumKey. Why not override __gt__?

according to docs sorted does use __lt__ for sorting,

The sort routines are guaranteed to use __lt__() when making comparisons between two objects.

Upvotes: 2

Related Questions