#!/usr/bin/python # -*- coding: utf-8 -*- import copy # Import the election results and group them by riding import csv ridings = dict() reader = csv.reader(open('EventResults.csv', 'rb'), delimiter=',') for row in reader: if row[1] not in ridings: ridings[row[1]] = {} ridings[row[1]][row[5]] = row # Guess at preference ballots using CBC's vote compass mapping = { 'Conservative': [ [1.00, [['Conservative'], ['Liberal'], ['Bloc QuÈbÈcois']]], ], 'Liberal': [ [0.90, [['Liberal'], ['Bloc QuÈbÈcois'], ['NDP-New Democratic Party', 'Green Party']]], [0.10, [['Liberal'], ['Conservative'], ['Bloc QuÈbÈcois']]], ], 'Bloc QuÈbÈcois': [ [0.35, [['Bloc QuÈbÈcois'], ['Liberal'], ['NDP-New Democratic Party', 'Green Party']]], [0.35, [['Bloc QuÈbÈcois'], ['NDP-New Democratic Party'], ['Liberal', 'Green Party']]], [0.30, [['Bloc QuÈbÈcois'], ['Green Party'], ['NDP-New Democratic Party', 'Liberal']]], ], 'NDP-New Democratic Party': [ [0.35, [['NDP-New Democratic Party'], ['Green Party'], ['Bloc QuÈbÈcois'], ['Liberal']]], [0.35, [['NDP-New Democratic Party'], ['Bloc QuÈbÈcois'], ['Liberal', 'Green Party']]], [0.30, [['NDP-New Democratic Party'], ['Liberal'], ['Green Party'], ['Bloc QuÈbÈcois']]], ], 'Green Party': [ [0.60, [['Green Party'], ['NDP-New Democratic Party'], ['Bloc QuÈbÈcois'], ['Liberal']]], [0.40, [['Green Party'], ['Bloc QuÈbÈcois'], ['NDP-New Democratic Party'], ['Liberal']]], ], } # Calculate the Schulze Method winner per riding winners = dict(zip(mapping.keys(), [0] * len(mapping))) from pyvotecore.schulze_method import SchulzeMethod for riding, riding_results in ridings.iteritems(): ballots = [] for party, candidate_results in riding_results.iteritems(): if candidate_results[5] in mapping: for map in mapping[candidate_results[5]]: ballot = copy.copy(map[1]) if 'Bloc QuÈbÈcois' not in riding_results and ['Bloc QuÈbÈcois'] in ballot: ballot.remove(['Bloc QuÈbÈcois']) ballots.append({ "count": int(map[0] * int(candidate_results[6])), "ballot": ballot, }) results = SchulzeMethod(ballots, ballot_notation = "grouping").as_dict() winners[results['winner']] += 1 print "%s,%s" % (riding, results['winner'])