I have a list of ballots that look like A>B>C>D>E and some of them that look like A>B>C=D=E. The ballots are in a text file and each ballot is on its own line. I want to assign point values to each candidate. For A>B>C>D>E, A should get 4 points for being in first, B should get 3, C 2, D 1, and E 0. For A>B>C=D=E, A should get 4 points, B should get 3, and because C, D, and E are tied they should split the remaining 3 points and so they each get 1. I want all the ballots in the text file to be counted and the votes be added up. What do you think is the easiest way to go about doing this?
Asked
Active
Viewed 3,328 times
2
-
1This site is for specific programming questions. The general idea should be rather obvious (read line, parse, assign points, sum it up) so get started and ask when you have problems *implementing* a step. – Jochen Ritzel Feb 11 '12 at 17:55
1 Answers
5
import itertools
import collections
def borda(ballot):
n = len([c for c in ballot if c.isalpha()]) - 1
score = itertools.count(n, step = -1)
result = {}
for group in [item.split('=') for item in ballot.split('>')]:
s = sum(next(score) for item in group)/float(len(group))
for pref in group:
result[pref] = s
return result
def tally(ballots):
result = collections.defaultdict(int)
for ballot in ballots:
for pref,score in borda(ballot).iteritems():
result[pref]+=score
result = dict(result)
return result
ballots = ['A>B>C>D>E',
'A>B>C=D=E',
'A>B=C>D>E',
]
print(tally(ballots))
yields
{'A': 12.0, 'C': 5.5, 'B': 8.5, 'E': 1.0, 'D': 3.0}

unutbu
- 842,883
- 184
- 1,785
- 1,677
-
11 years later, this still works! For anyone who comes across this, you just need to change this line: for pref,score in borda(ballot).iteritems(): to this: for pref,score in borda(ballot).items(): – Emac Apr 12 '23 at 19:39