Leetcode

From Yefu's notes
Jump to: navigation, search

LC179:

Lambda expression:

cmp=lambda x, y: int("".join([x,y]))-int("".join([y,x]))

Supporting cmp in list.sort in Python 3:

cmp=lambda x, y: int("".join([x,y]))-int("".join([y,x]))
k = self.cmp_to_key(cmp)
numstr.sort(reverse = True, key = k)

the cmp_to_key function is a receip from ActiveState:

def cmp_to_key(mycmp):
    'Convert a cmp= function into a key= function'
    class K(object):
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0  
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
    return K