Skip to content

Instantly share code, notes, and snippets.

@kra3
Created Sep 19, 2011
Embed
What would you like to do?
First implementation
def compare(x, y):
return y < x
def cmp_to_key(mycmp, col, covert_to_proper_datatype):
class K(object):
class K(object):
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(covert_to_proper_datatype(self.obj[col]), covert_to_proper_datatype(other.obj[col])) == False
def __gt__(self, other):
return mycmp(covert_to_proper_datatype(self.obj[col]), covert_to_proper_datatype(other.obj[col])) == True
def __eq__(self, other):
return mycmp(covert_to_proper_datatype(self.obj[col]), covert_to_proper_datatype(other.obj[col])) == False
return K
'''
test cases
>>>sorted([[5, 'Man', 1], [2, 'Arun', 6], [4, 'Dummy', 6], [1, 'Naveen', 3], [3, 'Bajsd', 7]], key=cmp_to_key(compare, 0, int), reverse=True)
>>>sorted([[5, 'Man', 1], [2, 'Arun', 6], [4, 'Dummy', 6], [1, 'Naveen', 3], [3, 'Bajsd', 7]], key=cmp_to_key(compare, 1, str), reverse=True) # w/ capitals into consideration
>>>sorted([[5, 'Man', 1], [2, 'Arun', 6], [4, 'Dummy', 6], [1, 'Naveen', 3], [3, 'Bajsd', 7]], key=cmp_to_key(compare, 1, lower), reverse=True) # w/o capitals into consideration
>>>sorted([[5, 'Man', "09/27/2011"], [2, 'Arun', "09/27/2011"], [4, 'Dummy', "09/27/2011"], [1, 'Naveen', "09/27/2011"], [3, 'Bajsd', "09/27/2011"]], key=cmp_to_key(compare, 2, lambda x: str(x).lower()), reverse=True)
from datetime import datetime as dt
>>>sorted([[5, 'Man', "4343-343-4343"], [2, 'Arun', "4343-343-4343"], [4, 'Dummy', "4343-343-4343"], [1, 'Naveen', "4343-343-4343"], [3, 'Bajsd', "4343-343-4343"]], key=cmp_to_key(compare, 2, lambda x: int(x.replace('-', '')))
>>>import xml.dom.minidom as m
>>>sorted([[5, 'Man', "<a href="#">12</a>"], [2, 'Arun',"<a href="#">1</a>"], [4, 'Dummy', "<a href="#">22</a>"], [1, 'Naveen', "<a href="#">342</a>"], [3, 'Bajsd', "<a href="#">45</a>"]], key=cmp_to_key(compare, 2, lambda x: m.parseString(x).childNodes[0].childNodes[0].nodeValue), reverse=True)
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment