Created
March 4, 2013 06:24
-
-
Save sureshvv/5080353 to your computer and use it in GitHub Desktop.
stable sort in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from random import choice | |
from operator import attrgetter | |
years = range(1992, 1995) | |
months = range(1, 3) | |
day = range(1, 3) | |
idx = range(2) | |
class A(object): | |
def __init__(self): | |
self.cat = 'cat%d' % (choice(idx),) | |
self.pub = '%s-%02d-%02d' % (choice(years), choice(months), choice(day)) | |
def __repr__(self): | |
return 'A cat: %s pub: %s' % (self.cat, self.pub) | |
def test1(): | |
out = [ A() ] * 100 | |
s1 = sorted(sorted(out, key=attrgetter('pub'), reverse=True), key=attrgetter('cat')) | |
prev = s1[0] | |
for i in s1[1:]: | |
assert((i.cat > prev.cat) or (i.cat == prev.cat and i.pub <= prev.pub)) | |
prev = i | |
if __name__ == '__main__': | |
test1() | |
~ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment