Skip to content

Instantly share code, notes, and snippets.

@sureshvv
Created March 4, 2013 06:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sureshvv/5080353 to your computer and use it in GitHub Desktop.
Save sureshvv/5080353 to your computer and use it in GitHub Desktop.
stable sort in python
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