Borda Count using python?
Question: 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?


Answer: 
    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}
    

