Salman
Salman

Reputation: 9

Not able to understand sorted in python

I have came across a code snippet to find the largest number from an array of string.However i am not able to understand how the compare is working ,since only we are passing one argument ,i.e the list ,but in lt method it is expecting 2 arguments.

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

lgs=''.join(sorted(map(str,[3, 30, 34, 5, 9]),key=Largenum))

Upvotes: 0

Views: 65

Answers (1)

tripleee
tripleee

Reputation: 189367

The sorted function obviously doesn't invoke the __lt__ method of this class directly. It will repeatedly invoke this method on individual pairs of members of the class in order to arrange them in sorted order. You can easily ascertain this by adding a simple print to the method.

>>> class Largenum(str):
...     def __lt__(x,y):
...         result = x+y > y+x
...         print('# __lt__({0!r}, {1!r}) => {2}'.format(x, y, result))
...         return result
...
>>> lgs=''.join(sorted(map(str,[3, 30, 34, 5, 9]),key=Largenum))
# __lt__('30', '3') => False
# __lt__('34', '30') => True
# __lt__('34', '30') => True
# __lt__('34', '3') => True
# __lt__('5', '3') => True
# __lt__('5', '34') => True
# __lt__('9', '3') => True
# __lt__('9', '34') => True
# __lt__('9', '5') => True
>>> lgs
'9534330'

Upvotes: 1

Related Questions