[Tutor] Sorting

Timothy M. Brauch tbrauch@tbrauch.com
Wed, 31 Jul 2002 02:22:05 -0400


Let's send this to the entire list this time...

> I muttered something about:
> > I would like to be able to sort the list of Participants in
> > Competition in specific ways.  I am pretty sure it can be done with
> > sort(cmpfunc), but I can't figure it out and documention on the
> > cmpfunc for sort seems to be lacking, or hard to find.  Here is an
> > example session of what I would like to have.
> [snip]
> > I tried writing sort_by_team() by scratch using if statements, but
> > somehow there is an error in my statements and possibly my identing,
> > but at something like 15 lines to sort a list, I think I am on the
> > wrong track.  So, I would greatly appreciate it if someone could
> > help me with the sort().

>From the extremely helpful Kalle:
> Generally, if you post more of your code and error messages, it is
> easier to help.  This time, I don't think that it mattered.  Just a
> tip for the future.

Each Participant also has age.  How I sorted alphabetically previously,
which did not work:

    def sort_by_alpha1(self):
        self.results = []
        for ca in xrange(len(self.roster)):
            CA = self.roster[ca]
            if len(self.results) == 0:
                self.results.append(CA)
            elif (CA.last+CA.first <
self.results[0].last+self.results[0].first):
                self.results.insert(0, CA)
            elif (CA.last+CA.first >
self.results[0].last+self.results[0].first):
                self.results.append(CA)
            else:
                for da in xrange(len(self.results)):
                    DA = self.results[da]
                    if (CA.last+CA.first > DA.last+DA.first):
                        pass
                    elif CA not in self.results:
                        self.results.insert(da, CA)
        return self.results

And how I do it now, which works:

    def cmp_alpha1(self, x, y):
        return cmp((x.last, x.first),
                   (y.last, y.first))

    def sort_alpha1(self):
        self.results = []
        for item in self.roster:
            self.results.append(item)
        self.results.sort(self.cmp_alpha1)
        return self.results

But, more importantly, I understand how the new way works.  And, it is much
cleaner and easier to understand.

Thanks all

 - Tim