Issue
Hi I was solving this question on leetcode [Given a list of non-negative integers, arrange them such that they form the largest number.] I saw this solution. I'm unable to understand how is the class LargerNumKey is working? Also, what is the purpose lt . and what are the variables x and y
class LargerNumKey(str):
def __lt__(x, y):
return x+y > y+x
class Solution:
def largestNumber(self, nums):
largest_num = ''.join(sorted(map(str, nums), key=LargerNumKey))
return '0' if largest_num[0] == '0' else largest_num
Solution
The __lt__
"dunder" method is what allows you to use the <
less-than sign for an object. It might make more sense written as follows:
class LargerNumKey(str):
def __lt__(self, other):
return self+other > other+self
# This calls into LargerNumKey.__lt__(LargerNumKey('0'), LargerNumKey('1'))
LargerNumKey('0') < LargerNumKey('1')
Behind the scenes when str
is subclassed, adding self+other
actually generates a str
object rather than a LargerNumKey
object, so you don't have infinite recursion problems defining an inequality on a type in terms of its own inequality operator.
The reason this works is perhaps more interesting:
- The first fact we need is that for any positive integers we actually have
(x>y) == (str(x)>str(y))
, so when the custom__lt__
is operating it's actually asking whether the integers represented by those string concatenations are greater or less than each other. - The second interesting fact is that the new inequality defined as such is actually transitive -- if
s<t
andt<u
thens<u
, so thesorted()
method is able to place all the numbers in the correct order by just getting the correct answer for each possible pair.
Answered By - Hans Musgrave
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.