Second python program: classes, sorting
WP
invalid at invalid.invalid
Sun Aug 10 15:11:03 EDT 2008
WP wrote:
Solved the problem, see below...
> Hello, here are some new things I've problems with. I've made a program
> that opens and reads a text file. Each line in the file contains a name
> and a score. I'm assuming the file has the correct format. Each
> name-score pair is used to instantiate a class Score I've written. This
> works fine, but here's my problem: After reading the file I have list of
> Score objects. Now I want to sort them in descending order. But no
> matter how I write my __cmp__ the order remains unchanged. I've
> determined that __cmp__ is called but it's only called twice for three
> list elements, isn't that odd?
>
> Complete program:
> class Score:
> def __init__(self, name_, score_):
> self.name = name_
> self.score = score_
>
> def __str__(self):
> return "Name = %s, score = %d" % (self.name, self.score)
>
> def __cmp__(self, other):
> print "in __cmp__"
> return self.score >= other.score
>
> name = ""
> score = 0
> # End class Score
>
> filename = "../foo.txt";
>
> try:
> infile = open(filename, "r")
> except IOError, (errno, strerror):
> print "IOError caught when attempting to open file %s. errno = %d,
> strerror = %s" % (filename, errno, strerror)
> exit(1)
>
> lines = infile.readlines()
>
> infile.close()
>
> lines = [l.strip() for l in lines] # Strip away trailing newlines.
>
> scores = []
>
> for a_line in lines:
> splitstuff = a_line.split()
>
> scores.append(Score(splitstuff[0], int(splitstuff[1])))
>
> scores.sort()
>
> for a_score in scores:
> print a_score
>
> Test file contents:
> Michael 11
> Hanna 1337
> Lena 99
>
> Output:
> in __cmp__
> in __cmp__
> Name = Michael, score = 11
> Name = Hanna, score = 1337
> Name = Lena, score = 99
>
> What am I doing wrong here?
>
> - Eric (WP)
I solved it, I rewrote __cmp__ to:
def __cmp__(self, other):
if self.score == other.score:
return cmp(self.name, other.name)
else:
return cmp(other.score, self.score)
This sorts so that score goes from highest to lowest. If two person have
the same score, I sort on names in alphabetical order. The following
text file:
Michael 11
Hanna 1337
Lena 99
Anna 99
yields (just as I want):
Name = Hanna, score = 1337
Name = Anna, score = 99
Name = Lena, score = 99
Name = Michael, score = 11
- Eric (WP)
More information about the Python-list
mailing list