[Edu-sig] fun with voting (by secret ballot)

kirby urner kirby.urner at gmail.com
Wed Jun 10 01:18:19 CEST 2015


"""
The code below derives from a thread on elections-wg at python.org
where we were talking about tie-breaking techniques.  There's a
well known way that's actually used, but I was inspired to think
about a game wherein the ballots are like playing cards in some
ways, each encoded with a unique prime.

I've got some notes in the moderator queue at math-teach (lots
of traffic), for which I'll share the URL.  More in this month's
elections-wg archive, public-facing.

It's just another way to introduce the Fundamental Theorem of
Arithmetic while reminding students of the composite vs. prime
distinction.  Standard fare.

(CL) copyleft, K. Urner / 4Dsolutions.net, 2015

"""


import random

class Ballot:
    """secret:  unique prime belongs to ballot itself
    """

    def __init__(self):
        self.dna = random.choice(pool_of_primes)  # this is done at the
store
        pool_of_primes.remove(self.dna)

    def vote(self, name, vote=1):
        self.candidate = name
        self.approve = vote

    def __repr__(self):
        return "Ballot with prime {}".format(self.dna)

pool_of_primes = [int(it) for it in """\
 2    3   5   7  11  13  17  19  23  29
31   37  41  43  47  53  59  61  67  71
73   79  83  89  97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239""".split()]  # 52 in a deck in this example

deck = [Ballot() for _ in range(52)]  # two extra ballots were not used
random.shuffle(deck) # dealt to voters (how many they get depends on how
many candidates)

# ballots coming in from voters all over the world!....

# each candidate on the slate gates same number of ballots cast

stackA = []
for _ in range(26):
    secret_ballot = deck.pop()
    secret_ballot.vote("Shrek")
    stackA.append(secret_ballot)

stackB = []
for _ in range(26):
    secret_ballot = deck.pop()
    secret_ballot.vote("Alice")
    stackB.append(secret_ballot)

# the Vote! a TIE, 25 for each candidate!

def break_tie(sA, sB):
    productA, productB = 1, 1
    for idx in range(len(sA)):
        productA = productA * sA[idx].dna
        productB = productB * sB[idx].dna
    if productA == productB:
        print("The impossible happened")
        raise Exception
    if productA > productB:
        print("Shrek wins!")
    else:
        print("Alice wins!")

break_tie(stackA, stackB)
print("The crowd roars")
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20150609/27bfd2eb/attachment.html>


More information about the Edu-sig mailing list