Python/Sorting
From charlesreid1
Python sorting: https://wiki.python.org/moin/HowTo/Sorting
Python sorted containers: http://www.grantjenks.com/docs/sortedcontainers/
Python bintrees implementation of dictionaries and lists: https://pypi.python.org/pypi/bintrees
>>> Student.__eq__ = lambda self, other: self.age == other.age >>> Student.__ne__ = lambda self, other: self.age != other.age >>> Student.__lt__ = lambda self, other: self.age < other.age >>> Student.__le__ = lambda self, other: self.age <= other.age >>> Student.__gt__ = lambda self, other: self.age > other.age >>> Student.__ge__ = lambda self, other: self.age >= other.age >>> sorted(student_objects) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
Another cool example: the keys we use to sort do not have to be part of the objects themselves, we can pass in a dictionary with labels and keys.
>>> students = ['dave', 'john', 'jane'] >>> newgrades = {'john': 'F', 'jane':'A', 'dave': 'C'} >>> sorted(students, key=newgrades.__getitem__) ['jane', 'dave', 'john']