2

I want to sort an array of numbers and return the largest number in string format. For example:

 Array = [5,1,9,30]

should return

'95301'

I have the following code that accomplishes it

class LargestKey(str):
    def __lt__(x, y):
    print("x",x,"y",y, x+y > y+x)
    return x+y > y+x

class Largest():
    def largestNumber(self, nums):
        mapResult = map(str, nums)
        num = ''.join(sorted(mapResult, key=LargestKey))

testNum = Largest()
print(testNum.largestNumber([5,1,9,30]))

According to the print in the LargestKey function, the output is:

x 1 y 5 False
x 9 y 1 True
x 9 y 1 True
x 9 y 5 True
x 30 y 5 False
x 30 y 1 True
95301

I don't understand why the checking with x = 9 and y = 1 is happening twice

3
  • 2
    Wouldn't 30 be the largest element in your array? May 20, 2020 at 19:56
  • I think it should return "30951" according to your idea May 20, 2020 at 20:58
  • 1
    Based on the example I assume the idea is to arrange the numbers such as to create the largest possible output number, in which case it should indeed start with the 9. Which would then mean we want a lexicographic comparison
    – cadolphs
    May 20, 2020 at 21:08

0

Your Answer

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

Browse other questions tagged or ask your own question.