Algorithmintro
Plurality voting
Also called first past the post, relative majority.
Elects the candidate ranked first by the most voters. It ignores all but the top choice of each voter.
- Time
- O(n + m) worst
- Space
- O(m) extra
- Where
- m = the number of candidates; n = the number of voters
- Model
- Word RAM
- Properties
- not comparison baseddeterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jean Charles de Borda, Allan Gibbard, Mark Satterthwaite, 1784
Plurality voting elects the candidate that the most voters rank first. It reads only the top entry of each ballot in a preference profile, counts the first places of each candidate, and breaks a tie by a fixed rule. It is the rule of most single-member elections in the United Kingdom, the United States, Canada and India, where it is called "first past the post". It is the fastest rule there is, but it can elect a candidate that a majority of the voters ranks last, and it rewards voters who do not vote for their true first choice.
In plain words
Each voter names one favourite. The candidate with the most votes wins, even when that is far less than half of the votes. A ballot says nothing about the second choice, so the rule cannot see that most voters may dislike the winner. When two similar candidates split the votes of their supporters, a third candidate that most voters like less can win. Voters know this, so many of them vote for the strongest candidate they can accept, and not for the one they like best.
The problem
There are candidates and voters. Voter has a ranking of all candidates, a tuple with the best candidate first, and the input is the profile . The output is one winner in . The plurality score of a candidate is
the number of voters who rank first. The plurality correspondence returns the set , and the resolute rule returns one element of it. Ties go to the candidate with the smallest index, as on every rule page of this area. In practice a ballot names only one candidate, and the code needs only that entry.
The algorithm
PLURALITY(P, m) ▷ P = (r_1, ..., r_n), each ranking best first- 1
s[a] ← 0 for each candidate a = 0, ..., m - 1 - 2
for each ranking r in P do - 3
s[r[1]] ← s[r[1]] + 1 ▷ only the top entry is read - 4
best ← max over a of s[a] - 5
W ← {a : s[a] = best} ▷ the plurality correspondence - 6
return the smallest candidate in W ▷ the fixed tie-breaking rule
Lines L1 to L3 are a counting pass: one counter per candidate, and one increment per voter. Lines L4 and L5 find all candidates with the highest count. Line L6 applies the tie-breaking rule. The code returns from a separate function, because the properties of the rule are cleaner on the correspondence: the tie-break by index favours candidate 0, so the resolute rule is not neutral, while the correspondence is.
Example
Take three candidates (indices 0, 1, 2) and nine voters:
| voters | ranking |
|---|---|
| 4 | |
| 3 | |
| 2 |
| step | state |
|---|---|
| L1 | |
| L2 to L3, the 4 voters | |
| L2 to L3, the 3 voters | |
| L2 to L3, the 2 voters | |
| L4 and L5 | , |
| L6 | return |
The winner has 4 of the 9 votes, less than half. The pairwise counts show what the ballots hide: beats by 5 to 4 and beats by 7 to 2, so is the Condorcet winner, and loses to both and by 5 to 4, so is the Condorcet loser. The Borda count gives , and the scores 8, 12 and 7, and instant-runoff voting removes and then elects by 5 to 4. The two voters can change the result: if they report , the scores become and wins, which they prefer to .
With three candidates, a Condorcet loser can win alone, with no tie, only when there are 7 or more voters; the smallest case is 3 voters , 2 voters and 2 voters . With the tie-break, 3 voters suffice: the ballots , and give one first place to each candidate, and the tie goes to , which loses to and to by 2 to 1.
Correctness
After the loop of lines L2 and L3 has read the first ballots, is the number of these ballots with on top, for every . This loop invariant holds at the start, where all counters are 0, and each pass adds 1 to exactly one counter, the one of the top of the new ballot. At the end , so line L5 builds and line L6 returns its smallest element. The proof in proofs/correctness.md also proves the properties below.
Proof: Correctness and properties of plurality votingfull
Let with , and let be a profile of rankings, each best first. Write for the plurality score and for the plurality correspondence. The resolute rule is .
Claim 1 (correctness). PLURALITY returns .
Proof. Invariant of the loop of lines L2 and L3: after the first ballots, for every . For this is line L1. If it holds for , the pass for ballot adds 1 to and to no other counter, and the set on the right gains the index for only, so it holds for . After passes, . Line L4 sets , line L5 builds , which is nonempty because a maximum is attained on the finite nonempty set , and line L6 returns .
Claim 2 (anonymity). For every permutation of the voters, , and so is the same on both profiles.
Proof. counts a set of ballots with a property that depends only on the ballot, so it does not depend on the order of the voters.
Claim 3 (neutrality of the correspondence). For a permutation of , let be the profile in which every ranking has each replaced by . Then .
Proof. The top of the renamed ballot is , so for every . The two score vectors have the same maximum, and attains it in exactly when attains it in .
The resolute rule is not neutral when : for the profile and the swap of 0 and 1, has the same two ballots in the other order, so .
Claim 4 (Pareto). If and every voter ranks above , then .
Proof. No ballot has on top, so . The scores add up to , so some candidate has a positive score, and .
Claim 5 (monotonicity). Let , and let be with one ballot changed by moving up one place and keeping the order of all other candidates. Then , and if then .
Proof. If is not in second place in , the top of does not change, and . If is in second place, the old top loses one first place and gains one: , , and every other score is the same. In both cases for every , because . So . Moreover : a candidate in has . So if is the smallest element of , it is also the smallest element of . Any raise of that keeps the order of the other candidates is a chain of such one-place moves, so the claim holds for it too.
Claim 6 (consistency). Let and be profiles of disjoint groups of voters, and let be the joined profile. If , then .
Proof. The scores add: . Let . Every candidate has a joined score at most , and a candidate attains this bound exactly when it attains in and in , that is, when it is in . That set is nonempty, so is the maximum of the joined scores and .
Claim 7 (two candidates). If , then exactly when ; that is, is majority rule with ties to candidate 0, and elects the Condorcet winner whenever there is one.
Proof. With two candidates the top of a ballot is the candidate preferred to the other one, so and . Candidate 0 is in exactly when , and then ; otherwise . A Condorcet winner has more than of these pairwise votes, so it is the unique maximizer.
Claim 8 (time). PLURALITY runs in time and extra space.
Proof. Line L1 writes counters. Each of the passes of the loop reads one entry and updates one counter in time. Lines L4, L5 and L6 each scan at most values. Only the counters and the set , of size at most , are stored.
Complexity
Line L1 takes time. The loop runs times, and each pass reads one entry and does one increment, so it takes time when a ballot gives random access to its first entry. Lines L4 to L6 each take time. The total is in the word RAM model, with counters of bits, and the extra space is the counters. If the input is a full profile, it has entries, but the rule never reads more than of them. No algorithm can do better than when , since any ballot that it does not read could change the winner.
Properties
These hold for every number of candidates. The proofs are in proofs/correctness.md, and the tests check each one by brute force over all profiles with up to 4 candidates and few voters.
- Anonymous. Reordering the voters does not change any score.
- Neutral, as a correspondence. Renaming the candidates renames the scores and the set . The resolute rule is not neutral: with one voter and one voter , it elects , and after the swap of the names it still elects .
- Pareto. If every voter ranks above , then no voter ranks first, so , while the winner has at least first places. So does not win when .
- Monotone. Raising the winner on one ballot either leaves all scores the same or moves one first place to . Both keep in and keep it the smallest maximizer, since no other score goes up.
- Consistent. If two disjoint groups of voters have winner sets and with , then the combined group has winner set , because the scores add. This is the consistency (reinforcement) axiom, and Young (1975) proved that, with anonymity, neutrality and a continuity condition, it characterizes the scoring rules, of which plurality is the simplest.
- Not Condorcet consistent, and it can elect the Condorcet loser. The example shows both failures.
- Not strategyproof for 3 or more candidates. The example shows a manipulation by the two voters . This is forced by the Gibbard-Satterthwaite theorem: plurality is onto and not a dictatorship, so some profile has a profitable false ballot.
- Majority rule for 2 candidates. With the plurality winner is the majority winner, and the rule is then strategyproof and Condorcet consistent. May's theorem characterizes it there.
Variants and improvements
- Plurality with runoff. If no candidate has more than half of the votes, hold a second round between the top two. The two-round system of French presidential elections works this way. It is still not Condorcet consistent, and it is not monotone.
- Instant-runoff voting. Ask for full rankings and remove the weakest candidate one at a time. See instant-runoff voting.
- Approval voting. Let each voter approve any set of candidates. See approval voting.
- Other scoring rules. Plurality gives 1 point to the top place and 0 to the others. The Borda count gives points to place , -approval gives 1 point to each of the top places, and the veto rule (anti-plurality) gives 1 point to every place except the last. All of them are consistent, and none of them is Condorcet consistent.
- Multiwinner forms. Single non-transferable vote and block voting elect the candidates with the most votes. The single transferable vote is the proportional form.
When to use it
Use plurality when ballots must be as simple as possible, the count must be done by hand or explained in one sentence, and the field has two strong candidates. Then the rule is almost majority rule. With three or more serious candidates, especially when two of them split one group of voters, use a rule that reads more of each ranking: instant-runoff voting if you want a majority in the last round, a Condorcet method such as the Copeland method or ranked pairs if you want the pairwise winner, or approval voting if you want a simple ballot that is safe for sincere voters.
Pitfalls
- An unstated tie rule. Line L6 is part of the rule. Python's
max(range(m), key=s.__getitem__)returns the first maximizer, which is the smallest index here, butmaxover a dictionary depends on the insertion order. State the rule, and return the set of line L5 when the caller must see the ties. - Plurality is not majority. In the example the winner has 4 of 9 votes. Code that checks "more than half" to decide the winner implements a different rule, one that can return no winner.
- Reading the wrong entry. In line L3 the top of the ballot is
r[0]in 0-based code. A ballot stored as a position vector (the place of each candidate) and not as a ranking gives wrong counts without any error. - Percentages in floating point. Compare the integer counts of line L4, not shares such as , where two equal counts can give shares that differ in the last bit after other arithmetic.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the algorithmic game theory pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Preference profiles, majority relations and brute force axiom checkers.
The candidates are 0, ..., m - 1. A ranking is a tuple of all m candidates, best first:
(2, 0, 1) means that 2 is preferred to 0 and 0 to 1. A profile is a tuple of n rankings,
one per voter. An approval ballot is a frozenset of candidates, and an approval profile is
a tuple of n ballots.
A rule is a function rule(profile, m). A resolute rule returns one candidate (an int); a
correspondence returns a nonempty frozenset of candidates. The checkers accept both: they
turn an int w into frozenset({w}).
Each checker takes the rule, m and n, and by default tries every profile of all_profiles(m,
n). Pass profiles= to check a given list of profiles instead (for example approval profiles,
or a random sample when the full domain is too large). Each checker returns None when the
property holds on every profile it tried, and else a counterexample tuple.
There is no voting rule in this module. Every count is an exact integer.
"""
from itertools import permutations, product
# ---------------------------------------------------------------- rankings and profiles
def all_rankings(m):
"""Return the list of the m! rankings of 0, ..., m - 1, in lexicographic order."""
return list(permutations(range(m)))
def all_profiles(m, n):
"""Yield every profile of n rankings of m candidates: (m!)^n profiles, voters ordered."""
return product(all_rankings(m), repeat=n)
def random_profile(rng, m, n):
"""Return a profile of n rankings drawn uniformly and independently (impartial culture)."""
return tuple(tuple(rng.sample(range(m), m)) for _ in range(n))
def position(r, a):
"""Return the position of candidate a in ranking r: 0 for the top."""
return r.index(a)
def prefers(r, a, b):
"""Return True if ranking r puts a above b."""
return r.index(a) < r.index(b)
def pairwise(profile, m):
"""Return the m by m matrix N with N[a][b] the number of voters who rank a above b."""
N = [[0] * m for _ in range(m)]
for r in profile:
for i, a in enumerate(r):
for b in r[i + 1:]:
N[a][b] += 1
return N
def margins(profile, m):
"""Return the m by m matrix of margins N[a][b] - N[b][a]."""
N = pairwise(profile, m)
return [[N[a][b] - N[b][a] for b in range(m)] for a in range(m)]
def condorcet_winner(profile, m):
"""Return the candidate with a positive margin over every other candidate, or None."""
M = margins(profile, m)
for a in range(m):
if all(M[a][b] > 0 for b in range(m) if b != a):
return a
return None
def weak_condorcet_winners(profile, m):
"""Return the frozenset of candidates whose margin over every other candidate is >= 0."""
M = margins(profile, m)
return frozenset(a for a in range(m) if all(M[a][b] >= 0 for b in range(m) if b != a))
def kendall_tau(r1, r2):
"""Return the number of pairs of candidates that r1 and r2 order differently."""
pos = {a: i for i, a in enumerate(r2)}
seq = [pos[a] for a in r1]
return sum(1 for i in range(len(seq)) for j in range(i + 1, len(seq)) if seq[i] > seq[j])
def is_single_peaked_on(profile, axis):
"""Return True if every ranking of the profile is single-peaked on the axis.
axis is a tuple of all candidates, left to right. A ranking is single-peaked on the axis
exactly when, for each k, its k best candidates form a contiguous block of the axis.
"""
where = {a: i for i, a in enumerate(axis)}
for r in profile:
lo = hi = where[r[0]]
for a in r[1:]:
p = where[a]
if p == lo - 1:
lo = p
elif p == hi + 1:
hi = p
else:
return False
return True
def lex_tiebreak(candidates):
"""Return the candidate with the smallest index: the default tie-breaking rule."""
return min(candidates)
def random_approval_profile(rng, m, n, p):
"""Return n approval ballots; each voter approves each candidate with probability p."""
return tuple(frozenset(a for a in range(m) if rng.random() < p) for _ in range(n))
def permute_profile(profile, pi):
"""Rename the candidates: candidate a becomes pi[a]. Works for rankings and approval ballots."""
out = []
for ballot in profile:
if isinstance(ballot, (set, frozenset)):
out.append(frozenset(pi[a] for a in ballot))
else:
out.append(tuple(pi[a] for a in ballot))
return tuple(out)
# ---------------------------------------------------------------- axiom checkers
def _as_set(result):
if isinstance(result, (set, frozenset)):
return frozenset(result)
return frozenset([result])
def _domain(m, n, profiles):
return all_profiles(m, n) if profiles is None else profiles
def _candidate_generators(m):
"""A transposition and an m-cycle: together they generate every permutation of the candidates."""
gens = []
if m >= 2:
swap = list(range(m))
swap[0], swap[1] = 1, 0
gens.append(tuple(swap))
if m >= 3:
gens.append(tuple((a + 1) % m for a in range(m)))
return gens
def check_anonymity(rule, m, n, profiles=None):
"""Check that permuting the voters does not change the result.
It tries the swap of voters 0 and 1 and the cyclic shift of the voters. These generate all
permutations, so on the full domain this is a complete test. Returns None or
(profile, permuted_profile).
"""
for P in _domain(m, n, profiles):
P = tuple(P)
if len(P) < 2:
continue
base = _as_set(rule(P, m))
others = [(P[1], P[0]) + P[2:], P[1:] + P[:1]]
for Q in others:
if _as_set(rule(Q, m)) != base:
return (P, Q)
return None
def check_neutrality(rule, m, n, profiles=None):
"""Check that renaming the candidates by pi renames the result by pi.
It tries a transposition and an m-cycle of the candidates, which generate all permutations.
A resolute rule with a fixed tie-breaking order usually fails this test; test its
correspondence instead. Returns None or (profile, pi).
"""
gens = _candidate_generators(m)
for P in _domain(m, n, profiles):
P = tuple(P)
base = _as_set(rule(P, m))
for pi in gens:
if _as_set(rule(permute_profile(P, pi), m)) != frozenset(pi[a] for a in base):
return (P, pi)
return None
def check_pareto(rule, m, n, profiles=None):
"""Check that no candidate b wins when every voter ranks some a above b.
Returns None or (profile, a, b).
"""
for P in _domain(m, n, profiles):
P = tuple(P)
W = _as_set(rule(P, m))
N = pairwise(P, m)
for b in W:
for a in range(m):
if a != b and N[a][b] == len(P):
return (P, a, b)
return None
def check_condorcet_consistency(rule, m, n, profiles=None):
"""Check that a Condorcet winner, when one exists, is the unique winner.
Returns None or (profile, condorcet_winner).
"""
for P in _domain(m, n, profiles):
P = tuple(P)
c = condorcet_winner(P, m)
if c is not None and _as_set(rule(P, m)) != frozenset([c]):
return (P, c)
return None
def _raise_once(r, w):
"""Return r with w moved up one place, or None if w is already on top."""
i = r.index(w)
if i == 0:
return None
s = list(r)
s[i - 1], s[i] = s[i], s[i - 1]
return tuple(s)
def check_monotonicity(rule, m, n, profiles=None):
"""Check that a winner stays a winner when one voter moves it up one place.
Every raise of w, with no other change in the relative order of the others, is a chain of
such one-place moves, so on the full domain this is a complete test. For a correspondence
the test is that w stays in the winning set. Returns None or (profile, raised_profile, w).
"""
for P in _domain(m, n, profiles):
P = tuple(P)
for w in _as_set(rule(P, m)):
for i, r in enumerate(P):
s = _raise_once(r, w)
if s is None:
continue
Q = P[:i] + (s,) + P[i + 1:]
if w not in _as_set(rule(Q, m)):
return (P, Q, w)
return None
def find_manipulation(rule, m, n, profiles=None):
"""Search for a voter who gets a strictly better winner by a false ranking.
The rule must be resolute (a correspondence must return one winner on every profile it
is called on). Returns None or (profile, voter, false_ranking): with the false ranking in
place of the voter's true one, the winner is one that the true ranking strictly prefers.
"""
rankings = all_rankings(m)
for P in _domain(m, n, profiles):
P = tuple(P)
w = _single(rule(P, m))
for i, r in enumerate(P):
if r[0] == w:
continue
for s in rankings:
if s == r:
continue
Q = P[:i] + (s,) + P[i + 1:]
if prefers(r, _single(rule(Q, m)), w):
return (P, i, s)
return None
def _single(result):
W = _as_set(result)
if len(W) != 1:
raise ValueError("find_manipulation needs a resolute rule")
return next(iter(W))
plurality_voting.py 34 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/plurality-voting/. The authors are listed in prov/WM09B3.jsonl.
from typing import Sequence
Ranking = Sequence[int]
def plurality_scores(profile: Sequence[Ranking], m: int) -> list[int]:
"""Return s with s[a] the number of voters who rank candidate a first.
The candidates are 0, ..., m - 1 and each ranking lists them best first. Only the first
entry of each ranking is read, so the time is O(n + m) for n voters.
"""
s = [0] * m # @line L1
for r in profile: # @line L2
s[r[0]] += 1 # @line L3
return s
def plurality_winners(profile: Sequence[Ranking], m: int) -> frozenset[int]:
"""Return the set of candidates with the most first places (the plurality correspondence)."""
s = plurality_scores(profile, m)
best = max(s) # @line L4
return frozenset(a for a in range(m) if s[a] == best) # @line L5
def plurality(profile: Sequence[Ranking], m: int) -> int:
"""Return the plurality winner; a tie goes to the candidate with the smallest index.
Precondition: m >= 1. With no voters every candidate has 0 first places, so candidate 0
wins. Time O(n + m), extra space O(m).
"""
return min(plurality_winners(profile, m)) # @line L6
test_plurality_voting.py 273 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/plurality-voting/. The authors are listed in prov/WM09B3.jsonl.
import itertools
import math
import random
from collections import Counter
import agtprefs
from agtprefs import (all_profiles, all_rankings, check_anonymity, check_condorcet_consistency,
check_monotonicity, check_neutrality, check_pareto, condorcet_winner,
find_manipulation, is_single_peaked_on, kendall_tau, lex_tiebreak, margins,
pairwise, permute_profile, position, prefers, random_approval_profile,
random_profile, weak_condorcet_winners)
from plurality_voting import plurality, plurality_scores, plurality_winners
A, B, C, D = 0, 1, 2, 3
# The worked example of the page: 4 voters a > b > c, 3 voters b > c > a, 2 voters c > b > a.
EXAMPLE = ((A, B, C),) * 4 + ((B, C, A),) * 3 + ((C, B, A),) * 2
CYCLE = ((A, B, C), (B, C, A), (C, A, B))
# ---------------------------------------------------------------- the shared helper
def test_helper_counts_rankings_and_profiles():
for m in range(0, 6):
rs = all_rankings(m)
assert len(rs) == math.factorial(m)
assert len(set(rs)) == len(rs)
assert rs == sorted(rs)
assert sum(1 for _ in all_profiles(3, 2)) == 36
assert sum(1 for _ in all_profiles(2, 3)) == 8
def test_helper_condorcet_cycle_check_value():
M = margins(CYCLE, 3)
assert M[A][B] == 1 and M[B][C] == 1 and M[C][A] == 1
assert M[B][A] == -1 and M[C][B] == -1 and M[A][C] == -1
assert condorcet_winner(CYCLE, 3) is None
assert weak_condorcet_winners(CYCLE, 3) == frozenset()
def test_helper_pairwise_matches_brute_force():
rng = random.Random(11)
for _ in range(300):
m, n = rng.randint(1, 5), rng.randint(0, 6)
P = random_profile(rng, m, n)
N = pairwise(P, m)
M = margins(P, m)
for a in range(m):
assert N[a][a] == 0
for b in range(m):
if a != b:
assert N[a][b] == sum(1 for r in P if prefers(r, a, b))
assert N[a][b] + N[b][a] == n
assert M[a][b] == -M[b][a]
cw = [a for a in range(m) if all(2 * N[a][b] > n for b in range(m) if b != a)]
assert condorcet_winner(P, m) == (cw[0] if cw else None)
weak = {a for a in range(m) if all(2 * N[a][b] >= n for b in range(m) if b != a)}
assert weak_condorcet_winners(P, m) == weak
if cw:
assert weak == {cw[0]}
def test_helper_positions_kendall_and_tiebreak():
rng = random.Random(12)
for _ in range(300):
m = rng.randint(1, 6)
r1 = tuple(rng.sample(range(m), m))
r2 = tuple(rng.sample(range(m), m))
for a in range(m):
assert r1[position(r1, a)] == a
want = sum(1 for a, b in itertools.combinations(range(m), 2)
if prefers(r1, a, b) != prefers(r2, a, b))
assert kendall_tau(r1, r2) == want == kendall_tau(r2, r1)
assert kendall_tau(r1, r1) == 0
assert kendall_tau(r1, tuple(reversed(r1))) == m * (m - 1) // 2
assert lex_tiebreak({3, 1, 2}) == 1
def _single_peaked_brute(r, axis):
where = {a: i for i, a in enumerate(axis)}
peak = where[r[0]]
for x, y in itertools.permutations(r, 2):
px, py = where[x], where[y]
# On one side of the peak, the candidate closer to the peak must be preferred.
if (py < px <= peak or peak <= px < py) and not prefers(r, x, y):
return False
return True
def test_helper_single_peaked_matches_definition():
for m in range(1, 6):
for axis in itertools.permutations(range(m)):
if m == 5 and axis != tuple(range(m)):
continue
count = 0
for r in all_rankings(m):
ok = is_single_peaked_on((r,), axis)
assert ok == _single_peaked_brute(r, axis)
count += ok
# A known count: 2^(m - 1) rankings are single-peaked on a fixed axis.
assert count == 2 ** (m - 1)
assert is_single_peaked_on(((1, 0, 2), (2, 1, 0)), (0, 1, 2))
assert not is_single_peaked_on(((1, 0, 2), (0, 2, 1)), (0, 1, 2))
def test_helper_random_profiles_and_permutation():
rng = random.Random(13)
P = random_profile(rng, 4, 50)
assert len(P) == 50 and all(sorted(r) == [0, 1, 2, 3] for r in P)
Q = random_approval_profile(random.Random(14), 5, 400, 0.3)
assert all(isinstance(b, frozenset) and b <= set(range(5)) for b in Q)
share = sum(len(b) for b in Q) / (5 * 400)
assert abs(share - 0.3) < 0.05
assert random_profile(random.Random(7), 3, 5) == random_profile(random.Random(7), 3, 5)
pi = (2, 0, 1)
assert permute_profile(((0, 1, 2),), pi) == ((2, 0, 1),)
assert permute_profile((frozenset({0, 2}),), pi) == (frozenset({2, 1}),)
def dictator(P, m):
return P[0][0] if P else 0
def constant(P, m):
return 0
def test_helper_checkers_on_dictatorship_and_constant_rule():
for m, n in [(3, 2), (3, 3), (2, 3)]:
# A dictatorship is neutral, Pareto, monotone and strategyproof, but not anonymous.
assert check_anonymity(dictator, m, n) is not None
assert check_neutrality(dictator, m, n) is None
assert check_pareto(dictator, m, n) is None
assert check_monotonicity(dictator, m, n) is None
assert find_manipulation(dictator, m, n) is None
# A constant rule is anonymous, monotone and strategyproof, but not neutral or Pareto.
assert check_anonymity(constant, m, n) is None
assert check_neutrality(constant, m, n) is not None
assert check_pareto(constant, m, n) is not None
assert check_monotonicity(constant, m, n) is None
assert find_manipulation(constant, m, n) is None
# With 3 voters, voter 0 can be outvoted by a majority that prefers b to the dictator's a.
P, c = check_condorcet_consistency(dictator, 3, 3)
assert condorcet_winner(P, 3) == c != P[0][0]
def test_helper_counterexamples_are_real():
P, Q = check_anonymity(dictator, 3, 2)
assert sorted(P) == sorted(Q) and dictator(P, 3) != dictator(Q, 3)
P, pi = check_neutrality(constant, 3, 2)
assert constant(permute_profile(P, pi), 3) != pi[constant(P, 3)]
P, a, b = check_pareto(constant, 3, 2)
assert b == 0 and all(prefers(r, a, b) for r in P)
def anti_plurality_top(P, m): # elects the candidate with the fewest first places
s = plurality_scores(P, m)
return min(range(m), key=lambda a: (s[a], a))
P, Q, w = check_monotonicity(anti_plurality_top, 3, 2)
assert anti_plurality_top(P, 3) == w != anti_plurality_top(Q, 3)
P, i, s = find_manipulation(anti_plurality_top, 3, 2)
Q = P[:i] + (s,) + P[i + 1:]
assert prefers(P[i], anti_plurality_top(Q, 3), anti_plurality_top(P, 3))
# ---------------------------------------------------------------- plurality voting
def test_worked_example():
assert plurality_scores(EXAMPLE, 3) == [4, 3, 2]
assert plurality(EXAMPLE, 3) == A
# b is the Condorcet winner, and the plurality winner a is the Condorcet loser.
assert condorcet_winner(EXAMPLE, 3) == B
M = margins(EXAMPLE, 3)
assert M[A][B] == -1 and M[A][C] == -1 and M[B][C] == 5
# The two voters c > b > a gain by voting b > c > a.
lie = ((A, B, C),) * 4 + ((B, C, A),) * 5
assert plurality(lie, 3) == B
def test_matches_counter_on_random_profiles():
rng = random.Random(21)
for _ in range(2000):
m, n = rng.randint(1, 6), rng.randint(0, 12)
P = random_profile(rng, m, n)
tops = Counter(r[0] for r in P)
s = plurality_scores(P, m)
assert s == [tops[a] for a in range(m)]
assert sum(s) == n
best = max(s)
W = {a for a in range(m) if tops[a] == best}
assert plurality_winners(P, m) == W
assert plurality(P, m) == min(W)
def test_edge_cases():
assert plurality((), 3) == 0 and plurality_winners((), 3) == {0, 1, 2}
assert plurality(((0,),), 1) == 0
assert plurality(((2, 1, 0), (1, 2, 0)), 3) == 1 # a tie of 1 and 2 goes to 1
assert plurality_winners(CYCLE, 3) == {A, B, C} and plurality(CYCLE, 3) == A
def test_axioms_by_brute_force():
for m, n in [(3, 3), (3, 4), (4, 2)]:
assert check_anonymity(plurality, m, n) is None
assert check_anonymity(plurality_winners, m, n) is None
assert check_neutrality(plurality_winners, m, n) is None
assert check_pareto(plurality, m, n) is None
assert check_monotonicity(plurality, m, n) is None
assert check_monotonicity(plurality_winners, m, n) is None
# The resolute rule with the fixed tie-break is not neutral.
P, pi = check_neutrality(plurality, 3, 2)
assert plurality(permute_profile(P, pi), 3) != pi[plurality(P, 3)]
def test_failures_by_search():
# Not Condorcet consistent, and open to manipulation, for 3 candidates.
P, c = check_condorcet_consistency(plurality, 3, 3)
assert plurality(P, 3) != c
P, i, s = find_manipulation(plurality, 3, 3)
Q = P[:i] + (s,) + P[i + 1:]
assert prefers(P[i], plurality(Q, 3), plurality(P, 3))
# With 3 candidates, a Condorcet loser can win alone (no tie) only with 7 or more voters.
def condorcet_loser(P, m):
M = margins(P, m)
losers = [a for a in range(m) if all(M[a][b] < 0 for b in range(m) if b != a)]
return losers[0] if losers else None
def loser_wins_alone(P):
W = plurality_winners(P, 3)
return len(W) == 1 and condorcet_loser(P, 3) in W
for n in range(1, 7):
assert not any(loser_wins_alone(P) for P in all_profiles(3, n))
smallest = ((A, B, C),) * 3 + ((B, C, A),) * 2 + ((C, B, A),) * 2
assert loser_wins_alone(smallest)
# With the tie-break, 3 voters suffice: a, b and c each have one first place, and a wins.
tied = ((A, B, C), (B, C, A), (C, B, A))
assert plurality(tied, 3) == A == condorcet_loser(tied, 3)
def test_consistency_by_brute_force():
# If two groups of voters have overlapping winner sets, the joined group elects the overlap.
for n1, n2 in [(1, 1), (1, 2), (2, 2)]:
groups1 = list(all_profiles(3, n1))
groups2 = list(all_profiles(3, n2))
checked = 0
for P1 in groups1:
W1 = plurality_winners(P1, 3)
for P2 in groups2:
both = W1 & plurality_winners(P2, 3)
if both:
assert plurality_winners(P1 + P2, 3) == both
checked += 1
assert checked > 0
def test_two_candidates_is_majority_rule():
for n in range(1, 8):
for P in all_profiles(2, n):
k = sum(1 for r in P if r[0] == 0)
assert plurality(P, 2) == (0 if 2 * k >= n else 1)
assert find_manipulation(plurality, 2, n) is None
assert check_condorcet_consistency(plurality, 2, n) is None
def test_helper_module_has_no_rule():
names = {x for x in dir(agtprefs) if not x.startswith("_")}
assert not any("plurality" in x or "borda" in x for x in names)
History
Plurality is the oldest and most common rule for elections. Borda, in a memoir printed in 1784, argued that it can elect a candidate whom a majority ranks last, and proposed his scoring rule in its place. Condorcet answered with the pairwise majority test. Gibbard (1973) and Satterthwaite (1975) proved that every onto rule with three or more possible winners that is not a dictatorship can be manipulated, so the strategic voting that plurality invites is not a defect of this rule alone. Young (1975) placed plurality in the family of scoring rules by the consistency axiom.
References
- Felix Brandt, Vincent Conitzer, Ulle Endriss, Jérôme Lang and Ariel D. Procaccia (eds.), Handbook of Computational Social Choice, Cambridge University Press, 2016, Chapter 2 (William S. Zwicker, Introduction to the theory of voting), Section 2.2 (plurality, Copeland and Borda) and Section 2.4 (scoring rules and runoffs)
- H. P. Young, Social choice scoring functions, SIAM Journal on Applied Mathematics 28(4) (1975), 824-838, the characterization of the scoring rules, of which plurality is one, by consistency with anonymity, neutrality and a continuity condition
- Jean-Charles de Borda, Mémoire sur les élections au scrutin, Histoire de l'Académie Royale des Sciences, année 1781 (printed 1784), 657-665, the argument that plurality can elect a candidate whom a majority ranks last
- Allan Gibbard, Manipulation of voting schemes, a general result, Econometrica 41(4) (1973), 587-601, the main theorem, which applies to plurality with three or more candidates
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag WM09B3 Edit this page History Report an error Markdown