#!/usr/bin/env python
import collections
import random
import statistics
def representative_vote(candidates: int) -> int:
"""Voters select at random from all available candidates."""
return random.randint(1, candidates)
def chamber_vote(candidates: int, representatives: int) -> int:
"""All representatives of the chamber vote. A majority wins; else the
candidate with the fewest voters is eliminated."""
tally = collections.Counter()
# Run vote
for _ in range(representatives):
tally[representative_vote(candidates)] += 1
# Check for majority
plurality = tally.most_common(1)[0]
if (representatives / 2) < plurality[1]:
return plurality[0]
# Eliminate candidate with fewest votes; identity does not matter here
return 0
def run1(candidates: int, representatives: int):
majority = 0
rounds = 0
viable_candidates = candidates
while not majority:
rounds += 1
majority = chamber_vote(viable_candidates, representatives)
viable_candidates -= 1
print(f"Majority in {rounds} rounds.")
def runmany(candidates: int, representatives: int, repeat: int):
results = []
for _ in range(repeat):
majority = 0
rounds = 0
viable_candidates = candidates
while not majority:
rounds += 1
majority = chamber_vote(viable_candidates, representatives)
viable_candidates -= 1
results.append(rounds)
average = statistics.mean(results)
print(f"Majority in {average} rounds on average")