![]() |
![]() First Summer 2006 |
class Candidate(object): def __init__(self, name): self.name = name self.points = 0 self.votes = 0 def add(self, points): self.points += points self.votes += 1 def report(self): return self.points def show(self): print self.name + " (" + str(self.points) + ", " + str(self.votes) + ")" votes = open("votes.txt", "r") lines = votes.readlines() votes.close() catalog = {} for line in lines: data = line.split() name = data[0] points = float(data[1]) if not catalog.has_key(name): catalog[name] = Candidate(name) (catalog[name]).add(points) for name in catalog.keys(): (catalog[name]).show()
Notice that this requires a data file (called votes.txt
):
Here's how this works if you play with it:Letterman 10 Oprah 5 Ferrell 8 Calvin 5 Oprah 8 Letterman 3 Ferrell 0 Calvin 0 Oprah 7 Letterman 5 Ferrell 8 Calvin 0 Perot 9.5 Oprah 5 Letterman 10 Calvin 2
>>> Perot (9.5, 1) Ferrell (16.0, 3) Letterman (28.0, 4) Calvin (7.0, 4) Oprah (25.0, 4) >>>