Skip to content

Instantly share code, notes, and snippets.

@wmmnola
Created April 27, 2020 18:26
Show Gist options
  • Save wmmnola/91ecc8f8b9a806ee245c94713eee281f to your computer and use it in GitHub Desktop.
Save wmmnola/91ecc8f8b9a806ee245c94713eee281f to your computer and use it in GitHub Desktop.
from random import gauss
from random import uniform
def dist2(party, voter):
progdist = (party.prog - voter.prog)**2
econdist = (party.econ - voter.econ)**2
mildist = (party.mil - voter.mil)**2
return progdist + econdist + mildist
class District:
def __init__(self, pop, parties):
self.voters = []
self.parties = parties
self.voteList = dict.fromkeys(self.parties, 0)
for x in range(pop):
self.voters.append(Voter())
def election(self):
for v in self.voters:
v.vote(self.parties, self)
winner = max(self.voteList, key=self.voteList.get)
winner.vote()
def count_vote(self, p):
self.voteList[p] += 1
class Voter:
def __init__(self):
self.prog = gauss(0, 100)
self.econ = gauss(0, 100)
self.mil = gauss(0, 100)
def vote(self, parties, con):
maxForce = 0
total_force = 0
localmass = gauss(20, 5)
maxParty = parties[0]
for p in parties:
f = (p.mass * localmass)/dist2(p, self)
if(f > maxForce):
maxForce = f
maxParty = p
con.count_vote(maxParty)
class Party:
def __init__(self, name, prog, econ, mil):
self.name = name
self.prog = prog
self.econ = econ
self.mil = mil
self.mass = 1
self.votes = 0
def vote(self):
self.votes += 1
self.mass *= uniform(0.5, 1.5)
n = 100
p2 = Party("The Liberal Party", 80, -20, 0)
p3 = Party("The Conservative Party", -20, 30, 0)
p4 = Party("People's Labour Party", 30, -80, 100)
p5 = Party("The Libertarians", 0, 60, -50)
p6 = Party("Culture Defence League", -80, 0, 60)
p7 = Party("The United Communist Front", 100, -100, 100)
parties = [p2, p3, p4, p5, p6, p7]
for i in range(n):
pop =gauss(100, 20)
d = District(int(pop), parties)
d.election()
for p in parties:
print("%s got %d seats" % (p.name, p.votes))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment