Newsgroups: comp.lang.python
From: Michael Scharf <Michael.Sch...@gmx.de>
Date: 1999/02/15
Subject: Re: mini-howto: sorting
Andrew Dalke wrote: [snip] > I know, it's somewhat silly, but I went through a little tutorial I would like to add yet another way of sorting: a little Let's take the Spam class: >>> class Spam: If you want to sort on two fields (e.g columns in tables or >>> def __init__(self, spam, eggs): >>> self.spam = spam >>> self.eggs = eggs >>> def __repr__(self): >>> return 'Spam(s=%s,e=%s)' %(repr(self.spam),repr(self.eggs)) >>> a = [Spam(1, 4), Spam(9, 3), Spam(4,6),Spam(4,4)] two attributes) you might use the composite comparer: >>> class CmpComposite: Now you can sort on Spam.spam, eggs.spam: >>> """Takes a list of compare functions and sorts in that order.""" >>> def __init__(self,*comparers): >>> self.comparers=comparers >>> def __call__(self,a,b): >>> for cmp in self.comparers: >>> c=cmp(a,b) >>> if c: >>> return c >>> return 0 >>> a.sort(CmpComposite(CmpAttr('spam'),CmpAttr('eggs'))) [Spam(s=1,e=4), Spam(s=4,e=4), Spam(s=4,e=6), Spam(s=9,e=3)] >>> print a Or you can sort on Spam.eggs, Spam.spam: >>> a.sort(CmpComposite(CmpAttr('eggs'),CmpAttr('spam'))) [Spam(s=9,e=3), Spam(s=1,e=4), Spam(s=4,e=4), Spam(s=4,e=6) >>> print a But what if you want to sort inverse on spam? Define a CompInverse: >>> class CmpInverse: Let's try it: >>> """Inverses the effect of a cmp.""" >>> def __init__(self,cmp): >>> self.cmp=cmp >>> def __call__(self,a,b): >>> return -self.cmp(a,b) >>> a.sort(CmpInverse(CmpAttr('spam'))) [Spam(s=9,e=3), Spam(s=4,e=6), Spam(s=4,e=4), Spam(s=1,e=4) OK, and now sort on eggs and inverse on spam: >>> a.sort(CmpComposite(CmpAttr('eggs'),CmpInverse(CmpAttr('spam')))) [Spam(s=9,e=3), Spam(s=4,e=4), Spam(s=1,e=4), Spam(s=4,e=6)] We can use our little framework to sort tables as well: >>> class CmpColumn: Let's now sort our table on column 0 and inverse on column 1: >>> """Sorts on an index of a sequence.""" >>> def __init__(self,column): >>> self.column=column >>> def __call__(self,a,b): >>> return cmp(a[self.column],b[self.column]) >>> table=[(1,2), (1,3), (1,0), (2,0), (0,3), (3,2)] >>> table.sort(CmpComposite(CmpInverse(CmpColumn(1)),CmpColumn(0))) [(0, 3), (1, 3), (1, 2), (1, 0), (2, 0), (3, 2)] >>> print table In terms of design patterns, we can identify CmpInverse [1] Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides: Michael
[
class CmpComposite: class CmpInverse: class CmpColumn: def test(): l=[3,5,6,71,2,3,4,5] table=[ print 'sort l[0], inv l[1]' print 'sort inv l[1], l[0]' class Spam: print "sort spam:" print "sort inv spam:" print "sort spam, eggs:" print "sort eggs, spam:" print "sort eggs, inv spam:" if __name__=='__main__': You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
| ||||||||||||||