# How Voting Systems Work 1, Exercise 1: a club vote, counted two ways # A club of 15 members ranks four candidates (assumed, invented numbers). # Find the plurality winner and its share, say whether it is a majority, # then play every head-to-head contest and look for a Condorcet winner. from collections import Counter from itertools import combinations profile = ( [("Ann", "Ben", "Cat", "Dan")] * 5 + [("Ben", "Cat", "Ann", "Dan")] * 4 + [("Cat", "Ben", "Dan", "Ann")] * 3 + [("Dan", "Cat", "Ben", "Ann")] * 3 ) names = sorted({c for b in profile for c in b}) total = len(profile) firsts = Counter(b[0] for b in profile) winner, top = firsts.most_common(1)[0] print("first choices:", dict(firsts)) print(f"plurality winner: {winner} with {top / total:.1%}; majority: {top > total / 2}") wins = {n: 0 for n in names} for x, y in combinations(names, 2): vx = sum(1 for b in profile if b.index(x) < b.index(y)) vy = total - vx print(f"{x} vs {y}: {vx} to {vy}") if vx > vy: wins[x] += 1 elif vy > vx: wins[y] += 1 print("head-to-head wins:", wins) condorcet = [n for n in names if wins[n] == len(names) - 1] print("Condorcet winner:", condorcet[0] if condorcet else "none") # Output when run: # first choices: {'Ann': 5, 'Ben': 4, 'Cat': 3, 'Dan': 3} # plurality winner: Ann with 33.3%; majority: False # Ann vs Ben: 5 to 10 # Ann vs Cat: 5 to 10 # Ann vs Dan: 9 to 6 # Ben vs Cat: 9 to 6 # Ben vs Dan: 12 to 3 # Cat vs Dan: 12 to 3 # head-to-head wins: {'Ann': 1, 'Ben': 3, 'Cat': 2, 'Dan': 0} # Condorcet winner: Ben