Subversion Repositories Remote Hare Voting

Rev

Rev 35 | Blame | Compare with Previous | Last modification | View Log | RSS feed

import string

# Parse input file
#
# input: lines of comma-separated values
#       nWinners, ...ignored fields...
#       candidate1, ballot1rank, ballot2rank, ...
#       candidate2, ballot1rank, ballot2rank, ...
#
# output: list of lists of ballots
#       [[1stcandbal1, 2ndcandbal1, ...], [1stcandbal2, 2ndcandbal2, ...], ...]

def parsestring(contents):
    lines = contents.splitlines()
    fields = string.split(lines[0], ",")
    nWinners = int(fields[0])

    votes = []
    for line in lines[1:]:
        fields = string.split(line, ",")
        candidate = fields[0]
        positions = fields[1:]
        ballotnumber = 0
        for position in positions:
            if position:
                votes.append([ballotnumber, int(position), candidate])
            ballotnumber = ballotnumber + 1

    votes.sort()

    ballots = []
    ballotnumber = ""
    ballot = ""
    for triple in votes:
        if ballotnumber == triple[0]:
            ballot.append(triple[2])
        else:
            if ballot:
                ballots.append(ballot)
            ballot = [triple[2]]
            ballotnumber = triple[0]

    ballots.append(ballot)
    return nWinners, ballots

def parsefile(filenameCSV):
    f = open(filenameCSV)
    s = f.read()
    return parsestring(s)