Subversion Repositories Remote Hare Voting

Rev

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

Rev Author Line No. Line
15 jtkorb 1
import string
2
 
3
# Parse input file
4
#
5
# input: lines of comma-separated values
21 jtkorb 6
#       nWinners, ...ignored fields...
7
#       candidate1, ballot1rank, ballot2rank, ...
8
#       candidate2, ballot1rank, ballot2rank, ...
15 jtkorb 9
#
10
# output: list of lists of ballots
21 jtkorb 11
#       [[1stcandbal1, 2ndcandbal1, ...], [1stcandbal2, 2ndcandbal2, ...], ...]
15 jtkorb 12
 
13
def parsestring(contents):
38 jtkorb 14
    lines = contents.splitlines()
15 jtkorb 15
    fields = string.split(lines[0], ",")
16
    nWinners = int(fields[0])
17
 
18
    votes = []
19
    for line in lines[1:]:
20
        fields = string.split(line, ",")
21
        candidate = fields[0]
21 jtkorb 22
        positions = fields[1:]
15 jtkorb 23
        ballotnumber = 0
21 jtkorb 24
        for position in positions:
15 jtkorb 25
            if position:
26
                votes.append([ballotnumber, int(position), candidate])
27
            ballotnumber = ballotnumber + 1
28
 
29
    votes.sort()
30
 
31
    ballots = []
32
    ballotnumber = ""
33
    ballot = ""
34
    for triple in votes:
35
        if ballotnumber == triple[0]:
21 jtkorb 36
            ballot.append(triple[2])
15 jtkorb 37
        else:
38
            if ballot:
39
                ballots.append(ballot)
40
            ballot = [triple[2]]
41
            ballotnumber = triple[0]
42
 
43
    ballots.append(ballot)
44
    return nWinners, ballots
45
 
46
def parsefile(filenameCSV):
47
    f = open(filenameCSV)
48
    s = f.read()
49
    return parsestring(s)