Skip to content

Instantly share code, notes, and snippets.

@AKST
Last active December 21, 2015 10:09
Show Gist options
  • Save AKST/6290167 to your computer and use it in GitHub Desktop.
Save AKST/6290167 to your computer and use it in GitHub Desktop.
Preferencial voting system simulator based on the australian voting system.
from copy import deepcopy
from random import shuffle
PARTIES = [
"LNP", "ALP", "GRN", "ASP", "BKAP",
"ON", "WLP", "PAP", "FF", "CD"
]
# functions
def gen_preferences():
prefences = deepcopy(PARTIES); shuffle(prefences)
return prefences
def reset(_dict):
for key in _dict:
_dict[key] = 0
def inc_key(_dict, key):
_dict[key] = _dict[key] + 1
return _dict
def most(_dict, comparison):
most, by = deepcopy(_dict).popitem()
for key in _dict:
if comparison(_dict[key], by):
most = key
by = _dict[key]
return most
def losing(_dict):
return most(_dict, lambda a, b: a < b)
def winning(_dict):
return most(_dict, lambda a, b: a > b)
def count_votes(preference_s, votes_for_parties):
reset(votes_for_parties)
for preference in preference_s:
inc_key(votes_for_parties, preference[0])
# simulation
SHOW_PROCESS = True
LOOK_UP = {
"LNP": "Liberial Nation Party",
"ALP": "Australian Labor Party",
"GRN": "Greens",
"ASP": "Australian Sex Party",
"BKAP": "Bob Katters Australia Party",
"ON": "One Nation",
"WLP": "Wikileaks Party",
"PAP": "Palmers Austrlia Party",
"FF": "Family First",
"CD": "Christian Democrats"
}
party_votes = {
"LNP": 0, "ALP": 0, "GRN": 0, "ASP": 0, "BKAP": 0,
"ON": 0, "WLP": 0, "PAP": 0, "FF": 0, "CD": 0
}
preferences = []
voting_round = 0
for i in range(0, 10):
preferences.append(gen_preferences())
while len(party_votes) > 1:
count_votes(preferences, party_votes)
loser = losing(party_votes)
party_votes.pop(loser)
if SHOW_PROCESS:
voting_round += 1
print("\nROUND", voting_round, "\n")
print("Least Votes:", LOOK_UP[loser])
print("Most Votes: ", LOOK_UP[winning(party_votes)], "\n")
for preference in preferences:
if SHOW_PROCESS: print(preference)
preference.remove(loser)
# result
print("\nThe " + LOOK_UP[winning(party_votes)] + " has won the election")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment