# How Voting Systems Work 4, Exercise 1: a pairwise matrix for a five-candidate club vote # 25 members rank five candidates (assumed, invented numbers). # Print the matrix, then say whether a Condorcet winner exists and whether it won on first choices. from collections import Counter groups = [ (7, ("Eve", "Dan", "Cy", "Bo", "Ana")), (6, ("Ana", "Bo", "Cy", "Dan", "Eve")), (5, ("Cy", "Dan", "Bo", "Eve", "Ana")), (4, ("Dan", "Cy", "Eve", "Bo", "Ana")), (3, ("Bo", "Cy", "Ana", "Dan", "Eve")), ] ballots = [r for count, r in groups for _ in range(count)] n = len(ballots) names = sorted(ballots[0]) wins = {(x, y): sum(1 for b in ballots if b.index(x) < b.index(y)) for x in names for y in names if x != y} print(" " + "".join(f"{y:>5}" for y in names)) for x in names: print(f"{x:>5} " + "".join(f"{'-' if x == y else wins[x, y]:>5}" for y in names)) winner = next((x for x in names if all(wins[x, y] > n / 2 for y in names if y != x)), None) print("Condorcet winner:", winner) first = Counter(b[0] for b in ballots) print("first choices:", dict(sorted(first.items()))) print("top on first choices:", first.most_common(1)[0][0]) # Output when run: # Ana Bo Cy Dan Eve # Ana - 6 6 9 9 # Bo 19 - 9 9 14 # Cy 19 16 - 14 18 # Dan 16 16 11 - 18 # Eve 16 11 7 7 - # Condorcet winner: Cy # first choices: {'Ana': 6, 'Bo': 3, 'Cy': 5, 'Dan': 4, 'Eve': 7} # top on first choices: Eve