Question on Python sort comparator


  • 0
    C

    Spend quite some time trying to figure out the difference between these two ways of using comparator:

    def comparator(a, b):
        return str(a) + str(b) > str(b) + str(a)
    
    nums = [0, 23, 32]
    a = sorted(nums, cmp = comparator, reverse = True )
    b = sorted(nums, cmp = lambda a,b : cmp(str(a)+str(b), str(b)+str(a)), reverse=True)
    

    The a is [0, 23, 32] whereas the b is [32, 23, 0]. Would someone please explain the difference?


  • 1

    Your comparator is supposed to return negative/zero/positive, not a boolean. Just like cmp:

    >>> help(cmp)
    Help on built-in function cmp in module __builtin__:
    
    cmp(...)
        cmp(x, y) -> integer
        
        Return negative if x<y, zero if x==y, positive if x>y.

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.