# Q-12 MCS 275 Tue 18 Apr 2017 : quiz12a.py
"""
Simulate the voting process with a list of threads.
Every thread has a probability p to vote yes.
If the function random() of the module random returns a number less than p,
then the vote is yes, otherwise the vote is no.
Define a class Voter, inheriting from the Thread class.
Every voter has a unique name: the string representation
of an integer number.
The tally of the votes is stored in a shared list.
"""
from threading import Thread
from random import random

class Voter(Thread):
    """
    Simulates a vote.
    """
    def __init__(self, name, bias, tally):
        """
        The name of the thread is the string representation
        of an integer number.  The bias of the voter is a float
        in the interval [0, 1], with the probability that the
        voter will vote yes.  The tally is a list, shared between
        all threads, initialized to False.
        """
        Thread.__init__(self, name=name)
        self.votes = tally
        self.probability = bias

    def run(self):
        """
        The voter votes.
        """
        idx = int(self.getName())
        vote = random()
        self.votes[idx] = (vote < self.probability)

def main():
    """
    Prompts the user for a number of voters.
    Starts the voting process.
    """
    nbr = int(input('Give the number of voters : '))
    tally = [False for _ in range(nbr)]
    voters = [Voter(str(k), random(), tally) for k in range(nbr)]
    for voter in voters:
        voter.start()
    for voter in voters:
        voter.join()
    print('Tally :', tally, 'sum =', sum(tally))

main()
