def tallySTV()

in pysteve/lib/plugins/stv.py [0:0]


def tallySTV(votes, issue, version = 2):
    rvotes = {}
    ovotes = votes
    # Cut out abstained votes.
    for vote in votes:
        if votes[vote].find("-") == -1:
            if version == 1:
                rvotes[vote] = votes[vote]
            else:
                rvotes[vote] = re.split(r"[\s,]", votes[vote])
    votes = rvotes
    m = re.match(r"stv(\d+)", issue['type'])
    if not m:
        raise Exception("Not an STV vote!")
    
    numseats = int(m.group(1))
    candidates = {}
    z = 0
    for c in issue['candidates']:
        candidates[makeLetter(z, version)] = c['name']
        z += 1

    # run the stv calc
    # Try version 2 first, fall back to version 1 if it breaks
    winners = []
    if version == 2:
        try:
            winners = run_vote(candidates, votes, numseats)
        except:
            return tallySTV(ovotes, issue, 1)
    else:
        winners = run_vote(candidates, votes, numseats)
        
    winnernames = []
    
    for c in winners:
        winnernames.append(candidates[c])

    # Return the data
    return {
        'votes': len(rvotes),
        'winners': winners,
        'winnernames': winnernames,
        'debug': debug,
        'version': version
    }, """
Winners:
 - %s
""" % "\n - ".join(winnernames)