Subversion Repositories Local Hare Voting

Rev

Details | 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
6
#	nWinners, ...ignored fields...
7
#	candidate1, ballot1rank, ballot2rank, ...
8
#	candidate2, ballot1rank, ballot2rank, ...
9
#
10
# output: list of lists of ballots
11
#	[[1stcandbal1, 2ndcandbal1, ...], [1stcandbal2, 2ndcandbal2, ...], ...]
12
 
13
def parsestring(contents):
14
    lines = string.split(contents, "\r\n")
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]
22
	positions = fields[1:]
23
        ballotnumber = 0
24
	for position in positions:
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]:
36
	    ballot.append(triple[2])
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)