Algorithmintro
Instant-runoff voting
Also called IRV, alternative vote, ranked-choice voting.
Repeatedly eliminates the candidate with the fewest first places and transfers its ballots until one candidate has a majority.
- Time
- O(L + m^2) worst
- Space
- O(n + m) extra
- Where
- L = the total length of the ballots; m = the number of candidates; n = the number of voters
- Model
- Word RAM
- Properties
- not comparison baseddeterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Thomas Hare, William Robert Ware, 1871
Instant-runoff voting (IRV) is a single-winner voting rule on ranked ballots that eliminates candidates one at a time. In each round every ballot counts for its highest-ranked candidate that is still in the race; if one candidate has more than half of these ballots it wins, and otherwise the candidate with the fewest ballots is eliminated and its ballots move to their next choices. It is the single-winner case of the single transferable vote, and it is called the alternative vote in the United Kingdom and ranked-choice voting in the United States. It fixes the vote splitting of plurality voting in many cases, but it is not monotone and it can eliminate the Condorcet winner.
In plain words
Each voter ranks the candidates from best to worst. First count only the top choices. If someone has more than half, that candidate wins. If not, drop the candidate with the fewest votes, and give each of its ballots to the next candidate on that ballot who is still in the race. Count again, and repeat until someone has more than half of the ballots that still count. It works like a series of runoff elections, but the voters vote only once.
The problem
There are candidates and voters. Voter gives a ballot , a sequence of distinct candidates, best first. A full ranking lists all candidates; a truncated ballot lists fewer, and it is exhausted when none of its candidates is still in the race. The input is the preference profile and the output is one winner.
For a set of continuing candidates, a ballot counts for its first entry in . Write for the number of ballots that count for , and for the number of ballots that are not exhausted. The rule starts with . If some has , or , it returns . Otherwise it removes from the candidate with the smallest . Among tied candidates it removes the one with the largest index, so that the smallest index wins a final tie, as on the other rule pages of this area.
The algorithm
The direct method recounts every ballot in each round. The method below keeps, for each candidate, the pile of ballots that count for it, and a pointer into each ballot. When a candidate is eliminated, only the ballots on its pile move, and each pointer only moves forward.
INSTANT-RUNOFF(P, m) ▷ P = (r_1, ..., r_n), each ballot best first- 1
C ← {0, ..., m - 1}; ptr[i] ← 1 for each voter i - 2
put each nonempty ballot i on pile[r_i[1]] - 3
loop - 4
T ← the sum of |pile[a]| over a in C ▷ ballots that are not exhausted - 5
if some a in C has 2 |pile[a]| > T, or C = {a} then - 6
return a - 7
x ← the a in C with the smallest |pile[a]|; the largest index among ties - 8
C ← C \ {x} - 9
for each ballot i on pile[x] do - 10
advance ptr[i] to the next entry of r_i that is in C - 11
if ptr[i] is within r_i then put i on pile[r_i[ptr[i]]], else i is exhausted
Lines L1 and L2 do the first count. Each pass of the loop is one round: lines L4 to L6 test for a winner, lines L7 and L8 eliminate the weakest candidate, and lines L9 to L11 transfer its ballots. The code also returns the counts of every round, which is how results are usually published.
Example
Take the nine voters of the plurality voting page:
| voters | ranking |
|---|---|
| 4 | |
| 3 | |
| 2 |
| round | action | ||||
|---|---|---|---|---|---|
| 1 | 4 | 3 | 2 | 9 | no one has 5 or more; eliminate , its 2 ballots go to |
| 2 | 4 | 5 | out | 9 | has 5 of 9 and wins |
Plurality elects here, which loses to both other candidates in pairs. IRV elects , the Condorcet winner, because the -voters' second choice now counts.
IRV can still miss the Condorcet winner. With 2 voters , 1 voter and 2 voters , the moderate beats by 3 to 2 and by 3 to 2, but it has the fewest first places. Round 1 has counts and eliminates , and then wins by 3 to 2. This is the center squeeze.
Two more failures, both with no tie for last place in any round, show that more support can hurt a candidate:
- Not monotone. With 6 voters , 2 voters , 4 voters and 5 voters , the first counts are , is eliminated, and wins by 11 to 6. If the 2 voters move to the top, the counts are , now is eliminated, its 4 ballots go to , and wins by 9 to 8. The winner lost by gaining votes.
- No-show paradox. With 2 voters , 4 voters and 3 voters , is eliminated first and wins by 5 to 4. If 2 more voters come to vote, the counts are , is eliminated, and wins by 7 to 4. The two new voters prefer to , so they would do better to stay at home.
Correctness
The method computes the rule of the problem section. The proof in proofs/correctness.md shows two invariants at line L4: the continuing set is the same as in the direct method, and for each , holds exactly the ballots that count for , so and . The second invariant holds because a ballot counts for exactly when its pointer is at ; eliminating changes the count of a ballot only if that ballot was on , and line L10 moves its pointer to the next entry in .
The proof also shows that stopping at a majority in line L5 does not change the winner. If , every other candidate in has fewer ballots than , so is never the one eliminated, and never goes down as shrinks. Eliminating to the end would also elect . The tests check the method against the direct recount, against elimination to the end, and on truncated ballots.
Proof: Correctness and properties of instant-runoff votingfull
Let with , and let be ballots, each a sequence of distinct candidates, best first. For , ballot counts for the first entry of that is in , if there is one. Let be the number of ballots that count for and .
The direct rule starts with and repeats: if some has , or , return ; else remove from the element with the smallest , the largest index among ties. Call the sequence of sets it visits .
Claim 1 (invariant). At the start of the -th pass of line L4, the set of the method is , and for every , is the set of ballots that count for with respect to . For every ballot on , , and every entry of before position is outside .
Proof. By induction on . For , , every nonempty ballot counts for its first entry, and line L2 puts it on that pile with . Empty ballots count for nobody and are on no pile.
Assume the claim at pass and that the method does not return. Then , so line L7 picks the same as the direct rule, and line L8 makes . Take a ballot . If it counted for some , all its entries before are outside , hence outside , and , so it still counts for ; the method does not touch it. If it counted for , it is on , and line L10 moves to the first later entry in ; all entries before it are outside (the ones before by the hypothesis, itself, and the skipped ones by line L10). So the ballot now counts for , and line L11 puts it on that pile, or it is exhausted and counts for nobody. If it counted for nobody, it still counts for nobody. Clearing completes the step.
Claim 2 (correctness). The method returns the winner of the direct rule.
Proof. By Claim 1, in each pass line L4 computes and line L5 tests the same condition as the direct rule. If it holds, both return the same . Otherwise both remove the same . Each pass removes one candidate, so after at most passes and the method returns.
Claim 3 (early stop). If for some , then eliminating until one candidate is left, by the same elimination rule, also elects .
Proof. While is in and , every has , so is not the candidate of smallest count and is not removed. Removing another candidate does not decrease , since a ballot that counts for still counts for , and it does not increase , since a ballot can only become exhausted. So the condition holds in every later round, and is the last candidate left.
Claim 4 (majority criterion). If more than ballots have first, the rule returns in round 1.
Proof. , and no other candidate can also have more than half.
Claim 5 (Condorcet loser criterion). Assume full rankings. If loses to every other candidate in pairs, that is for all , where is the number of voters who rank above , then the rule does not return (for ).
Proof. With full rankings no ballot is exhausted, so . If the rule returns at a round with or by a strict majority, then ; every ballot that counts for ranks above every other member of , so for any , , a contradiction. Otherwise can only be returned when , so the rule must pass through a round with for some . In that round each ballot counts for the one of that it ranks higher, so . The two counts add up to , so has a strict majority and is returned. In no case is returned.
Claim 6 (Pareto). Assume full rankings and . If every voter ranks above , the rule does not return .
Proof. While , no ballot counts for , because comes before on every ballot. Suppose is removed in some round while is in . Then , so had no ballots and its removal moves none: stays 0. From then on, as long as is in , the smallest count in is 0, so every removed candidate has count 0 and moves no ballots, and stays 0. Since , some candidate in has a positive count, so never has a majority, and would need all candidates with ballots to be removed, which never happens while , with count 0, is still in. Hence is removed before the end, and it is not returned.
Claim 7 (anonymity). The winner does not depend on the order of the ballots.
Proof. Every quantity that the direct rule uses, and , counts ballots and does not depend on their order.
Claim 8 (two candidates). If and the ballots are full rankings, the rule returns 0 exactly when .
Proof. In round 1, and . If the rule returns 0, and if it returns 1. If , neither has a majority, the tie rule removes 1, and the rule returns 0.
Claim 9 (time). The method runs in time with , plus for the setup, and in extra space.
Proof. Lines L1 and L2 take time. Each round removes one candidate, so there are at most rounds, and lines L4 to L8 cost per round. In lines L9 to L11 each unit of work moves a pointer forward by one entry, and the pointer of ballot never passes the end of , so the total over all rounds is . A ballot is on at most one pile at a time, so the piles use space, and the pointers use .
Complexity
Lines L1 and L2 take time. There are at most rounds, and lines L4 to L8 take time per round, so in total. In lines L9 to L11, every step of a pointer moves it forward in its ballot, and a ballot moves to a new pile only after such a step, so all transfers of the whole count take time, where . The total is , which is for full rankings, linear in the input when . The extra space is the pointers and the piles, which together hold each ballot once: . The direct recount costs per round and in total.
Properties
The tests check each claim by brute force over all profiles of full rankings with 3 candidates and up to 5 voters, or 4 candidates and up to 3 voters, and find the counterexamples by search. The proofs of the positive claims are in proofs/correctness.md.
- Anonymous. The order of the voters does not matter.
- Neutral, as a correspondence. The set of candidates that win under some way of breaking elimination ties (parallel-universe tie-breaking) is renamed with the candidates. The resolute rule is not neutral, because of the tie-break by index.
- Majority criterion. A candidate ranked first by more than half of the voters wins in round 1.
- Condorcet loser criterion. With full rankings, IRV never elects a candidate that loses to every other candidate in pairs. In the last round only two candidates remain, so their counts are their pairwise counts, and an early stop needs a majority of first places.
- Pareto. With full rankings, a candidate that every voter ranks below some has no ballots while is in the race, and is eliminated before any candidate with ballots.
- Not Condorcet consistent. The center squeeze above is a counterexample.
- Not monotone. With 3 candidates, the smallest failure by one voter raising the winner one place has 7 voters and goes through a tie. Doron and Kronick (1977) described this failure for the single transferable vote.
- Not participation-safe. The no-show example above is a counterexample.
- Manipulable, but hard to manipulate. The search finds a profile with 3 candidates and 3 voters where one voter gains by a false ranking, as the Gibbard-Satterthwaite theorem predicts. Bartholdi and Orlin (1991) proved that it is NP-complete to decide whether a voter can make a given candidate win, so the voting manipulation problem for IRV has no known polynomial-time algorithm.
- Majority rule for 2 candidates. With the rule elects the majority winner, ties to candidate 0.
Variants and improvements
- Two-round system. Eliminate all candidates except the top two at once, and hold a second election. It needs a second trip to the polls, and the voters can change their minds.
- Contingent vote and supplementary vote. One count, then all but the top two are eliminated and their ballots transferred. The supplementary vote limits each ballot to two choices.
- Batch elimination. Eliminate at once all candidates whose combined count is below the count of the next candidate. None of them can win, so the winner does not change, and the count is shorter.
- Coombs' method. Eliminate the candidate ranked last by the most voters, not the one with the fewest first places.
- Baldwin's and Nanson's methods. Eliminate by the Borda count: the candidate with the lowest score, or all candidates below the average. Both are Condorcet consistent.
- Single transferable vote. For seats, a candidate is elected when it reaches a quota, and its surplus ballots are transferred too. See single transferable vote.
When to use it
Use IRV for a single-winner election with ranked ballots when you want the winner to have a majority of the ballots that still count in the last round, and you want to avoid a second trip to the polls. It removes most spoiler effects of plurality voting when one or two minor candidates are far behind. If the main concern is to elect the candidate that beats every other in pairs, use a Condorcet method such as the Copeland method or ranked pairs. If ballots must be simple, consider approval voting.
Pitfalls
- Majority of what. With truncated ballots, "more than half" can mean half of all ballots or half of the ballots that are not exhausted. When ballots are exhausted, the first rule can find no majority and must go on to the last two candidates, while the second rule stops earlier. If the first rule then eliminates to the end, the two rules elect the same candidate, but the published rounds differ. This page uses the continuing ballots; state which rule you use.
- The elimination tie rule. A tie for last place decides who is eliminated and can decide the winner. Laws often use earlier rounds or a lot. Fix the rule and test it; a scan that keeps the first minimum and one that keeps the last minimum can give different winners on the same profile.
- Recounting from scratch. Recounting all ballots in each round costs . With piles and pointers the work is .
- Skipping eliminated candidates once. When a ballot moves, its next choice may already be eliminated. Line L10 must skip every eliminated candidate, not just one.
- The name ranked-choice voting. In the United States it means IRV, but it is also used for the single transferable vote and for any rule on ranked ballots. Say which rule you mean.
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))
instant_runoff_voting.py 58 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/instant-runoff-voting/. The authors are listed in prov/P7TC87.jsonl.
from typing import Sequence
Ranking = Sequence[int]
def instant_runoff_rounds(profile: Sequence[Ranking], m: int) -> tuple[int, list[tuple[list[int], int]]]:
"""Run instant-runoff voting and return (winner, rounds).
The candidates are 0, ..., m - 1 (m >= 1). Each ballot ranks distinct candidates, best
first; a ballot may be truncated and leave some candidates out, and it is exhausted when
none of its candidates is still in the race. Each entry of rounds is (count, x): count[a]
is the number of ballots on the pile of a in that round (0 for eliminated candidates), and
x is the candidate eliminated in that round, or -1 in the last round.
The count stops when a continuing candidate has more than half of the ballots that are not
exhausted, or when one candidate is left. Among the continuing candidates with the fewest
ballots, the one with the largest index is eliminated, so that the smallest index wins a
final tie. Time O(L + m^2) with L the total length of the ballots, which is O(n m + m^2)
for full rankings; extra space O(n + m).
"""
continuing = [True] * m # @line L1
ptr = [0] * len(profile)
piles: list[list[int]] = [[] for _ in range(m)]
for i, r in enumerate(profile): # @line L2
if len(r) > 0:
piles[r[0]].append(i)
left = m
rounds = []
while True: # @line L3
active = sum(len(piles[a]) for a in range(m) if continuing[a]) # @line L4
count = [len(piles[a]) if continuing[a] else 0 for a in range(m)]
for a in range(m): # @line L5
if continuing[a] and (2 * count[a] > active or left == 1):
rounds.append((count, -1))
return a, rounds # @line L6
x = -1
for a in range(m): # @line L7
if continuing[a] and (x == -1 or count[a] <= count[x]):
x = a
rounds.append((count, x))
continuing[x] = False # @line L8
left -= 1
for i in piles[x]: # @line L9
r = profile[i]
ptr[i] += 1
while ptr[i] < len(r) and not continuing[r[ptr[i]]]: # @line L10
ptr[i] += 1
if ptr[i] < len(r): # @line L11
piles[r[ptr[i]]].append(i)
piles[x] = []
def instant_runoff(profile: Sequence[Ranking], m: int) -> int:
"""Return the instant-runoff winner, with the tie rules of instant_runoff_rounds."""
return instant_runoff_rounds(profile, m)[0]
test_instant_runoff_voting.py 202 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/instant-runoff-voting/. The authors are listed in prov/P7TC87.jsonl.
import itertools
import random
from agtprefs import (all_profiles, all_rankings, check_anonymity, check_condorcet_consistency,
check_monotonicity, check_neutrality, check_pareto, condorcet_winner,
find_manipulation, margins, permute_profile, prefers, random_profile)
from instant_runoff_voting import instant_runoff, instant_runoff_rounds
A, B, C, D = 0, 1, 2, 3
def naive_irv(profile, m):
"""Recount every ballot from scratch in each round, with the same tie rules."""
cont = set(range(m))
while True:
count = {a: 0 for a in cont}
for r in profile:
tops = [a for a in r if a in cont]
if tops:
count[tops[0]] += 1
active = sum(count.values())
for a in sorted(cont):
if 2 * count[a] > active or len(cont) == 1:
return a
low = min(count.values())
cont.remove(max(a for a in cont if count[a] == low))
def put_winners(profile, m):
"""The winners under every way of breaking elimination ties (parallel universes)."""
out = set()
def run(cont):
if len(cont) == 1:
out.update(cont)
return
count = {a: 0 for a in cont}
for r in profile:
tops = [a for a in r if a in cont]
if tops:
count[tops[0]] += 1
low = min(count.values())
for x in [a for a in cont if count[a] == low]:
run(cont - {x})
run(frozenset(range(m)))
return frozenset(out)
def condorcet_loser(P, m):
M = margins(P, 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 multisets(m, n):
return [tuple(c) for c in itertools.combinations_with_replacement(all_rankings(m), n)]
# The worked example: the nine voters of the plurality page.
EXAMPLE = ((A, B, C),) * 4 + ((B, C, A),) * 3 + ((C, B, A),) * 2
def test_worked_example():
w, rounds = instant_runoff_rounds(EXAMPLE, 3)
assert rounds == [([4, 3, 2], C), ([4, 5, 0], -1)]
assert w == B == condorcet_winner(EXAMPLE, 3)
def test_matches_naive_recount():
rng = random.Random(41)
for _ in range(3000):
m, n = rng.randint(1, 6), rng.randint(0, 11)
if rng.random() < 0.5:
P = random_profile(rng, m, n)
else: # truncated ballots
P = tuple(tuple(rng.sample(range(m), rng.randint(0, m))) for _ in range(n))
assert instant_runoff(P, m) == naive_irv(P, m)
def test_early_stop_equals_running_to_the_end():
# Stopping at a majority of the continuing ballots gives the same winner as eliminating
# until one candidate is left.
def to_the_end(P, m):
cont = set(range(m))
while len(cont) > 1:
count = {a: sum(1 for r in P if [x for x in r if x in cont][:1] == [a]) for a in cont}
low = min(count.values())
cont.remove(max(a for a in cont if count[a] == low))
return cont.pop()
rng = random.Random(42)
for _ in range(1500):
m, n = rng.randint(1, 6), rng.randint(1, 11)
P = random_profile(rng, m, n)
assert instant_runoff(P, m) == to_the_end(P, m)
def test_rounds_are_consistent():
rng = random.Random(43)
for _ in range(500):
m, n = rng.randint(1, 6), rng.randint(1, 11)
P = random_profile(rng, m, n)
w, rounds = instant_runoff_rounds(P, m)
out = set()
for count, x in rounds:
assert all(count[a] == 0 for a in out)
assert sum(count) == n # full rankings are never exhausted
if x >= 0:
assert count[x] == min(count[a] for a in range(m) if a not in out)
out.add(x)
assert len(rounds) <= m and w not in out
def test_edge_cases():
assert instant_runoff((), 3) == 0
assert instant_runoff(((), ()), 2) == 0
assert instant_runoff(((0,),), 1) == 0
assert instant_runoff(((1, 0), (0, 1)), 2) == 0 # a final tie goes to the smaller index
assert instant_runoff(((2,), (1,), (1,)), 3) == 1 # truncated ballots
def test_majority_and_condorcet_loser_criteria():
for m, n in [(3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 2), (4, 3)]:
for P in all_profiles(m, n):
w = instant_runoff(P, m)
for a in range(m):
if 2 * sum(1 for r in P if r[0] == a) > n:
assert w == a
assert w != condorcet_loser(P, m)
assert w in put_winners(P, m)
def test_axioms_by_brute_force():
for m, n in [(3, 3), (3, 4), (4, 2), (4, 3)]:
assert check_anonymity(instant_runoff, m, n) is None
assert check_pareto(instant_runoff, m, n) is None
assert check_neutrality(put_winners, m, n) is None
# The resolute rule with the fixed tie-break is not neutral.
assert check_neutrality(instant_runoff, 3, 2) is not None
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 instant_runoff(P, 2) == (0 if 2 * k >= n else 1)
assert find_manipulation(instant_runoff, 2, n) is None
def test_not_condorcet_consistent():
# The center squeeze: b beats a and c in pairs, but has the fewest first places.
P = ((A, B, C),) * 2 + ((B, A, C),) + ((C, B, A),) * 2
assert condorcet_winner(P, 3) == B
assert instant_runoff_rounds(P, 3) == (A, [([2, 1, 2], B), ([3, 0, 2], -1)])
found = check_condorcet_consistency(instant_runoff, 3, 3)
assert found is not None and instant_runoff(found[0], 3) != found[1]
def test_not_monotone():
# With 3 candidates, the smallest failure of monotonicity by a one-place raise has 7
# voters, and it goes through a tie.
for n in range(1, 7):
assert check_monotonicity(instant_runoff, 3, n, profiles=multisets(3, n)) is None
P, Q, w = check_monotonicity(instant_runoff, 3, 7, profiles=multisets(3, 7))
assert instant_runoff(P, 3) == w != instant_runoff(Q, 3)
# A failure with no ties: 6 a > b > c, 2 b > a > c, 4 b > c > a, 5 c > a > b. a wins.
# If the 2 voters b > a > c move a to the top, b drops below c and c wins.
P = ((A, B, C),) * 6 + ((B, A, C),) * 2 + ((B, C, A),) * 4 + ((C, A, B),) * 5
Q = ((A, B, C),) * 8 + ((B, C, A),) * 4 + ((C, A, B),) * 5
assert instant_runoff_rounds(P, 3) == (A, [([6, 6, 5], C), ([11, 6, 0], -1)])
assert instant_runoff_rounds(Q, 3) == (C, [([8, 4, 5], B), ([8, 0, 9], -1)])
def test_no_show_paradox():
# 2 a > c > b, 4 b > c > a, 3 c > b > a: c wins. Two more voters a > c > b make b win,
# and they prefer c to b, so they do better by staying home.
P = ((A, C, B),) * 2 + ((B, C, A),) * 4 + ((C, B, A),) * 3
assert instant_runoff_rounds(P, 3) == (C, [([2, 4, 3], A), ([0, 4, 5], -1)])
Q = P + ((A, C, B),) * 2
assert instant_runoff_rounds(Q, 3) == (B, [([4, 4, 3], C), ([4, 7, 0], -1)])
assert prefers((A, C, B), C, B)
def test_manipulable():
P, i, s = find_manipulation(instant_runoff, 3, 3)
Q = P[:i] + (s,) + P[i + 1:]
assert prefers(P[i], instant_runoff(Q, 3), instant_runoff(P, 3))
def test_renaming_and_put_on_ties():
# With 3 voters and one first place each, the tie rule decides; the parallel-universe
# correspondence returns every candidate.
P = ((A, B, C), (B, C, A), (C, A, B))
assert put_winners(P, 3) == {A, B, C}
pi = (2, 0, 1)
assert put_winners(permute_profile(P, pi), 3) == {pi[a] for a in put_winners(P, 3)}
History
Thomas Hare in Britain and Carl Andrae in Denmark devised the single transferable vote in the 1850s, as a rule to elect several members. The single-winner form, in which a candidate is elected by a majority and the weakest is eliminated, is usually credited to the American architect William Robert Ware, about 1871. Australia has used it for its House of Representatives since 1918, Ireland uses it to elect its president, and the American state of Maine first used it in 2018. Doron and Kronick (1977) showed that the rule is not monotone, and Bartholdi and Orlin (1991) showed that manipulating it is NP-complete, a first example of computational hardness as a barrier to strategic voting.
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.4 (Condorcet extensions, scoring rules and run-offs)
- Gideon Doron and Richard Kronick, Single transferable vote: an example of a perverse social choice function, American Journal of Political Science 21(2) (1977), 303-311, the failure of monotonicity
- John J. Bartholdi III and James B. Orlin, Single transferable vote resists strategic voting, Social Choice and Welfare 8(4) (1991), 341-354, the proof that it is NP-complete to decide whether a voter can manipulate the single-winner rule
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 P7TC87 Edit this page History Report an error Markdown