Algorithmcore
Single transferable vote
Also called STV.
Elects a committee from ranked ballots by quota, transferring surplus votes of elected candidates and votes of eliminated ones.
- Time
- O(L + m^2) worst
- Space
- O(n + m) extra
- Where
- L = the total length of the ballots; k = the number of seats; m = the number of candidates; n = the number of voters
- Model
- Word RAM
- Properties
- not comparison baseddeterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Carl Andrae, Thomas Hare, Henry Richmond Droop, 1857
The single transferable vote (STV) elects a committee of members from ranked ballots. A candidate is elected when its tally reaches a quota, and its surplus above the quota moves on to the next choices of its voters. When nobody reaches the quota, the weakest candidate is eliminated and its ballots move on. With one seat it is instant-runoff voting; with more seats it gives each large enough group of like-minded voters a share of the seats. It uses quotas, but it is a voting rule on ballots, not an apportionment method for parties.
In plain words
Each voter ranks the candidates. A candidate needs a fixed number of votes, the quota, to win a seat. Count the first choices. If a candidate has the quota or more, it wins, and the votes it does not need are passed on to the next choices on its ballots, each ballot at a reduced value. If nobody has the quota, the candidate with the fewest votes drops out, and its ballots go to their next choices at full value. Repeat until all seats are filled. Few votes are wasted: a vote helps elect one candidate, or it moves on.
The problem
There are candidates , voters and seats. Voter gives a ballot , a sequence of distinct candidates, best first, which may be truncated. The input is the preference profile and ; the output is a list of winners, in the order of election.
Let be the number of nonempty ballots. The Droop quota is , the smallest whole number such that no candidates can all reach it. The Hare quota is . Each ballot has a weight , at first 1, and counts for its first candidate that is still continuing. The tally is the sum of the weights of the ballots that count for .
The rule of this page moves surpluses by the inclusive Gregory method: when is elected with , every ballot that counts for moves on with its weight multiplied by . Ties are broken by index: the largest tally is elected with the smallest index among ties, and the smallest tally is eliminated with the largest index among ties, as on the instant-runoff page. When the continuing candidates are no more than the empty seats, they are all elected.
The algorithm
As in instant-runoff voting, each candidate has a pile of the ballots that count for it, and each ballot has a pointer to its current entry. MOVE advances the pointer of ballot to its next entry that is still in , puts on that pile and adds to that tally. If there is no such entry, the ballot is exhausted.
SINGLE-TRANSFERABLE-VOTE(P, m, k) ▷ P = (r_1, ..., r_n), each ballot best first- 1
V ← the number of nonempty ballots; q ← ⌊V/(k + 1)⌋ + 1 - 2
C ← {0, ..., m - 1}; W ← empty list; w[i] ← 1 and ptr[i] ← 1 for each ballot i - 3
put each nonempty ballot i on pile[r_i[1]]; t(a) ← the sum of w[i] over pile[a] - 4
while |W| < k and C is not empty do - 5
if |C| ≤ k - |W| then - 6
append C to W by decreasing t, then by index; return W - 7
e ← the a in C with the largest t(a), the smallest index among ties; if t(e) ≥ q then - 8
C ← C \ {e}; append e to W - 9
f ← (t(e) - q) / t(e) - 10
for each ballot i on pile[e] do w[i] ← f · w[i]; MOVE(i) - 11
else x ← the a in C with the smallest t(a), the largest index among ties - 12
C ← C \ {x} - 13
for each ballot i on pile[x] do MOVE(i) - 14
return W
Lines L1 to L3 compute the quota and do the first count. Each pass of the loop is one round: line L5 fills the last seats when no choice is left, lines L7 to L10 elect a candidate and pass on its surplus, and lines L11 to L13 eliminate a candidate and pass on its ballots at full weight. All weights are exact fractions. The code also returns a log of the tallies of every round, which is how counts are published. With the Hare quota and no ballots, , so the code also asks on line L7.
Example
Five candidates and 20 ballots compete for seats, so .
| ballots | ranking |
|---|---|
| 9 | |
| 2 | |
| 4 | |
| 3 | |
| 2 |
| round | action | |||||
|---|---|---|---|---|---|---|
| 1 | 9 | 2 | 4 | 3 | 2 | elect ; |
| 2 | 5 | 4 | 3 | 2 | eliminate | |
| 3 | 5 | 4 | 5 | eliminate | ||
| 4 | 5 | 9 | 2 left for 2 seats: elect , then |
In round 1, has and is elected. Its surplus is , so each of its 9 ballots moves to with weight , and gets . In round 2 nobody has 6, and has the fewest votes; its 2 ballots go to . In round 3, is eliminated and its 4 ballots go to . Then two candidates are left for two seats. The committee is . The 11 voters of the and group get two seats and the 9 voters of the , and group get one. If the three candidates with the most first choices won, the committee would be , and the larger group would get only one seat.
Correctness
The proof shows four things. The piles and pointers give the same tallies as a recount of all ballots in each round, because a ballot that counts for a continuing candidate keeps counting for it. The rule returns distinct winners. Votes are conserved: the continuing tallies, for each candidate elected by quota, and the weight of the exhausted ballots always sum to , so each candidate elected by quota keeps exactly votes. And the rule has proportionality for solid coalitions: if at least voters rank all members of a set above everyone else, with , then at least members of are elected. The proof of the last fact uses only conservation and , which holds for both quotas.
Proof: Correctness and properties of the single transferable votefull
Let be the candidates and the number of seats. The input is a list of ballots, each a sequence of distinct candidates, best first, possibly truncated. Empty ballots are dropped, and is the number of the other ballots. The quota is (Droop) or (Hare). In both cases . Every claim below holds for both quotas.
The direct rule keeps a set of continuing candidates, a list of winners and a weight for each ballot, with at the start. Ballot counts for the first entry of that is in , if there is one; otherwise it is exhausted. Let be the sum of the weights of the ballots that count for . One round of the direct rule is:
- If , append all of to by decreasing and then by index, and stop.
- Else let be the candidate of with the largest , the smallest index among ties. If and , multiply the weight of each ballot that counts for by , remove from and append it to .
- Else remove from the candidate with the smallest , the largest index among ties.
The rule stops when or is empty. The test file has an implementation of this direct rule, which recounts all ballots in every round.
Claim 1 (invariant). At the start of each pass of line L4, the set , the list and the weights of the method are those of the direct rule after the same number of rounds. For every , is the set of ballots that count for , and the tally of is the sum of their weights. For each ballot on , , and every entry of before position is outside .
Proof. By induction on the number of rounds. At the start, , every weight is 1, and line L3 puts every ballot on the pile of its first entry, with the pointer at that entry. Assume the claim before a round. Then the tallies are the values of the direct rule, so line L5 makes the same test as step 1, and line L7 picks the same as step 2. In the fill case both rules append the same list and stop.
In the elect case, line L8 removes and appends it to , as in step 2. The ballots that count for are those of . Line L10 multiplies their weights by , as in step 2, and moves each one. A move advances the pointer past every entry that is not in , so the ballot goes to the pile of its first entry in the new , or it is exhausted. A ballot that counted for some still counts for , because its earlier entries were outside the old and so are outside the new one; the method does not touch it. If , the ballots of have weight 0 in the direct rule from now on, and the method drops them; in both rules they add 0 to every later tally. The tally of each pile grows by the weights of the ballots that join it, so the tallies stay correct.
The eliminate case is the same with : line L11 picks the same candidate as step 3, line L12 removes it, and line L13 moves the ballots of with their weights unchanged.
Claim 2 (termination and output). The method stops after at most rounds and returns distinct candidates.
Proof. Each round that does not stop removes one candidate from , so there are at most rounds. A candidate enters only when it leaves , so the winners are distinct. Let be the number of empty seats. If , step 1 applies in the first round and gets all candidates. If , then starts at . An election lowers and by 1 each, so it keeps . An elimination lowers by 1. So the count either fills all seats in step 2, or it reaches and step 1 elects exactly the candidates that are left. In both cases .
Claim 3 (conservation of votes). At the start of each round,
where is the total weight of the exhausted ballots. So each candidate elected in step 2 keeps exactly votes.
Proof. At the start the tallies sum to , is empty and . An elimination moves each ballot of the eliminated candidate, with its weight, to another pile or to the exhausted ballots, so the sum does not change. An election of removes from the tallies; the ballots of go on with the total weight , to other piles or to , and grows by 1, which adds . So the sum does not change.
Claim 4 (proportionality for solid coalitions). Let and with . Suppose at least ballots rank all members of above every other candidate (in any order among themselves, and with any continuation, or none, after ). Then the rule elects at least members of .
Proof. Let be the set of these ballots, so , and let be the number of members of in . We show that the following holds at the start of every round in which :
(a) every ballot of counts for a member of ;
(b) ;
(c) .
Note first that (a) follows from (c): each ballot of lists all of before any other candidate, so if is not empty, its first continuing entry is in . At the start, , so the sum in (b) is at least , and (c) is . Assume (a), (b) and (c) at the start of a round of step 2 or step 3, and that still holds after it. First (c): an election of a member of lowers both sides of (c) by 1, and an election outside changes neither. An elimination happens only when every continuing candidate has . Then, by (b), the members of have tallies that sum to at least , each below , so there are at least of them, and at least are left after one is removed. So (c) holds after the round, and (a) with it. Now (b): by (a), before and after the round, no ballot of is exhausted and none lies on the pile of a candidate outside . So the weight of , which is at the start of the count, is split between the piles of and the votes kept by the elected members of . Each of them keeps votes in total by Claim 3, so at most from , and (b) holds after the round.
Now suppose that when the count stops. If it stops in step 1, all of is elected, and by (c) this adds at least members of , so after all. If it stops in step 2 with , then winners are outside , each elected in step 2, and by (a) none of the votes that each keeps comes from . So the ballots outside have a total weight of at least :
This is a contradiction. The count cannot stop with empty while , by (c). So at least members of are elected.
Claim 5 (one seat). With and the Droop quota, the rule elects the winner of instant-runoff voting with the same elimination tie rule.
Proof. With , , which is more than . Step 1 applies only when one candidate is left, and step 2 elects only when , which is at least half of the ballots that are not exhausted. While nobody has , steps 3 of both rules remove the same candidate. If step 2 elects with , where is the number of ballots that are not exhausted, then by Claim 3 of the instant-runoff page, eliminating to the end also elects , and so does the instant-runoff rule, which stops at the first majority of the ballots that still count.
Complexity
Let be the total length of the ballots. Each move advances a pointer, so all moves together take steps. There are at most rounds, and each one finds a largest and a smallest tally in time. The total is arithmetic operations and extra space, besides the ballots. The weights are fractions, and each surplus transfer multiplies some of them by a new factor, so their bit length can grow with the number of transfers. Counting rules used in practice round the weights to a fixed number of decimals, which keeps every operation on a word RAM at the cost of small errors.
Properties
- Proportionality for solid coalitions. As stated above. With the Droop quota, a group of more than voters who agree on the top of their ballots is sure of a seat. This is the reason the Droop quota is used.
- One seat. With the Droop quota is a majority of all ballots, and the rule elects the winner of instant-runoff voting.
- Not monotone. It inherits this from instant-runoff voting. With 6 ballots , 2 ballots , 4 ballots , 5 ballots and one seat, is eliminated and wins. If the 2 voters of move to the top, is eliminated, its 4 ballots go to , and wins.
- Anonymity. Only the multiset of ballots matters. The tie rule by index makes it not neutral in ties.
- Manipulation. It is NP-complete to decide whether one voter can make a given candidate win by a false ballot (Bartholdi and Orlin 1991). See the voting manipulation problem.
- No Condorcet guarantee. Like instant-runoff voting, it can eliminate a candidate that beats every other in pairs.
Variants and improvements
- The quota. The Hare quota is larger. It can change who gets a surplus and so the result. With the 8 ballots , , , , twice and twice , and , the Droop quota 3 elects 2 and then 1, and the Hare quota 4 elects 2 and then 0.
- The surplus rule. The inclusive Gregory method moves all ballots of the elected candidate at a reduced weight. The last-parcel rule moves only the ballots that arrived last. Some laws, as in Ireland, move whole ballots taken from the pile, so the choice of ballots can change the result. The weighted inclusive Gregory method, used for Scottish local elections, takes the weight of each ballot into account, as this page does.
- Meek's method. Elected candidates keep exactly by an iteration over keep factors, and eliminated or elected candidates are skipped on every ballot, also on ballots that moved before. The quota is computed again as ballots become exhausted. It needs a computer.
- Other proportional rules. For approval ballots, proportional approval voting, Phragmen's sequential method and the method of equal shares give proportionality in the sense of justified representation. For party lists, use an apportionment method such as the D'Hondt method.
When to use it
Use STV to elect several members from one district when voters rank candidates and you want proportional results without parties or lists. Groups of voters get seats in proportion to their size, and voters can rank across party lines. It needs ranked ballots and a central count, and the count is hard to check by hand when surpluses are fractional. For a single seat, use instant-runoff voting or a Condorcet method. If the goal is a committee that represents every voter by one member, see the Chamberlin-Courant rule.
Pitfalls
- Which quota. The integer Droop quota, the exact Droop quota and the Hare quota give different counts. With the exact quota , candidates can all reach it. State the quota.
- Count the transfer weight, not the ballots. A ballot that moved from a surplus has a weight below 1. A count of ballots instead of weights gives wrong tallies in the later rounds.
- Exhausted ballots. With truncated ballots, the tallies can sum to less than , and no one may reach the quota. Line L5 then fills the last seats with the continuing candidates. Without it, the count can stop with empty seats.
- Ties. The order of elections and the elimination ties can decide seats. Laws often look at earlier rounds or draw lots. Fix the rule and test it.
- Rounding. Exact fractions grow. If the law rounds weights to a fixed number of decimals, do the same, and do it at the step the law gives, or the published counts will not match.
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))
single_transferable_vote.py 101 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/single-transferable-vote/. The authors are listed in prov/CH8C0N.jsonl.
from fractions import Fraction
from typing import Sequence
Ranking = Sequence[int]
def droop_quota(v: int, k: int) -> Fraction:
"""Return the Droop quota floor(v / (k + 1)) + 1 for v valid ballots and k seats."""
return Fraction(v // (k + 1) + 1)
def hare_quota(v: int, k: int) -> Fraction:
"""Return the Hare quota v / k for v valid ballots and k seats."""
return Fraction(v, k)
def stv_count(profile: Sequence[Ranking], m: int, k: int, quota: str = "droop"):
"""Run the single transferable vote and return (winners, log).
The candidates are 0, ..., m - 1 and k >= 1 is the number of seats. Each ballot ranks
distinct candidates, best first, and may be truncated. Surplus votes move by the
inclusive Gregory rule: every ballot on the pile of an elected candidate e moves on with
its weight multiplied by (t(e) - q) / t(e), where t(e) is the tally of e and q the quota.
In a round, the continuing candidate with the largest tally is elected if it has at least
q, ties to the smallest index; otherwise the continuing candidate with the smallest tally
is eliminated, ties to the largest index. When the continuing candidates are no more than
the empty seats, all of them are elected, by tally and then by index.
winners lists the elected candidates in the order of election, min(k, m) of them. Each
log entry is (action, candidate, tally), where action is "elect", "eliminate" or "fill",
and tally is the list of the tallies of the continuing candidates at that moment (None for
the others). All weights are exact fractions.
"""
valid = [r for r in profile if len(r) > 0]
v = len(valid)
q = droop_quota(v, k) if quota == "droop" else hare_quota(v, k) # @line L1
continuing = [True] * m # @line L2
weight = [Fraction(1)] * v
ptr = [0] * v
piles: list[list[int]] = [[] for _ in range(m)]
tally = [Fraction(0)] * m
for i, r in enumerate(valid): # @line L3
piles[r[0]].append(i)
tally[r[0]] += 1
left = m
winners: list[int] = []
log = []
def move(i: int) -> None:
r = valid[i]
ptr[i] += 1
while ptr[i] < len(r) and not continuing[r[ptr[i]]]:
ptr[i] += 1
if ptr[i] < len(r):
piles[r[ptr[i]]].append(i)
tally[r[ptr[i]]] += weight[i]
while len(winners) < k and left > 0: # @line L4
snapshot = [tally[a] if continuing[a] else None for a in range(m)]
if left <= k - len(winners): # @line L5
rest = sorted((a for a in range(m) if continuing[a]), key=lambda a: (-tally[a], a))
for a in rest:
continuing[a] = False
winners.append(a)
log.append(("fill", a, snapshot))
return winners, log # @line L6
e = -1
for a in range(m):
if continuing[a] and (e == -1 or tally[a] > tally[e]):
e = a
if tally[e] >= q and tally[e] > 0: # @line L7
continuing[e] = False # @line L8
left -= 1
winners.append(e)
log.append(("elect", e, snapshot))
f = (tally[e] - q) / tally[e] # @line L9
if f > 0:
for i in piles[e]: # @line L10
weight[i] *= f
move(i)
piles[e] = []
else:
x = -1
for a in range(m): # @line L11
if continuing[a] and (x == -1 or tally[a] <= tally[x]):
x = a
continuing[x] = False # @line L12
left -= 1
log.append(("eliminate", x, snapshot))
for i in piles[x]: # @line L13
move(i)
piles[x] = []
return winners, log # @line L14
def single_transferable_vote(profile: Sequence[Ranking], m: int, k: int, quota: str = "droop") -> list[int]:
"""Return the k winners of the single transferable vote, in the order of election."""
return stv_count(profile, m, k, quota)[0]
test_single_transferable_vote.py 237 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/single-transferable-vote/. The authors are listed in prov/CH8C0N.jsonl.
import random
import unittest
from fractions import Fraction
from itertools import combinations
from agtprefs import all_rankings, check_anonymity, random_profile
from single_transferable_vote import droop_quota, hare_quota, single_transferable_vote, stv_count
A, B, C, D, E = range(5)
EXAMPLE = [(A, B)] * 9 + [(B, A)] * 2 + [(C, D)] * 4 + [(D, C)] * 3 + [(E, D)] * 2
def recount_stv(profile, m, k, quota="droop"):
"""A second count: it recomputes every tally from the ballots in each round.
It also checks that the total weight is conserved in every round. It returns the winners.
"""
ballots = [list(r) for r in profile if len(r) > 0]
v = len(ballots)
q = droop_quota(v, k) if quota == "droop" else hare_quota(v, k)
weight = [Fraction(1)] * v
cont = set(range(m))
winners = []
kept = Fraction(0)
def top(r):
for a in r:
if a in cont:
return a
return None
while len(winners) < k and cont:
t = {a: Fraction(0) for a in cont}
exhausted = Fraction(0)
for r, w in zip(ballots, weight):
a = top(r)
if a is None:
exhausted += w
else:
t[a] += w
assert sum(t.values()) + kept + exhausted == v
if len(cont) <= k - len(winners):
winners.extend(sorted(cont, key=lambda a: (-t[a], a)))
return winners
best = max(t.values())
e = min(a for a in cont if t[a] == best)
if t[e] >= q and t[e] > 0:
f = (t[e] - q) / t[e]
for i, r in enumerate(ballots):
if top(r) == e:
weight[i] *= f
kept += q
cont.discard(e)
winners.append(e)
else:
worst = min(t.values())
cont.discard(max(a for a in cont if t[a] == worst))
return winners
def irv_to_the_end(profile, m):
"""Instant runoff run until one candidate is left; elimination ties to the largest index."""
cont = set(range(m))
while len(cont) > 1:
t = {a: 0 for a in cont}
for r in profile:
for a in r:
if a in cont:
t[a] += 1
break
worst = min(t.values())
cont.discard(max(a for a in cont if t[a] == worst))
return cont.pop()
def random_ballots(rng, m, n, truncate):
out = []
for r in random_profile(rng, m, n):
if truncate:
r = r[: rng.randint(0, m)]
out.append(r)
return out
def solid_coalitions(profile, m, q):
"""Yield (S, j): the ballots that rank all of S above every other candidate number at least j q."""
for size in range(1, m + 1):
for S in combinations(range(m), size):
s = set(S)
count = sum(1 for r in profile if len(r) >= size and set(r[:size]) == s)
j = int(Fraction(count) / q)
if j >= 1:
yield s, j
class TestQuotas(unittest.TestCase):
def test_droop_and_hare(self):
self.assertEqual(droop_quota(20, 3), 6)
self.assertEqual(droop_quota(100, 1), 51)
self.assertEqual(droop_quota(99, 2), 34)
self.assertEqual(hare_quota(20, 3), Fraction(20, 3))
for v in range(1, 60):
for k in range(1, 6):
q = droop_quota(v, k)
self.assertGreater((k + 1) * q, v)
self.assertLessEqual(k * q, v + k)
class TestWorkedExample(unittest.TestCase):
def test_rounds(self):
winners, log = stv_count(EXAMPLE, 5, 3)
self.assertEqual(winners, [A, D, B])
self.assertEqual([(act, c) for act, c, _ in log], [("elect", A), ("eliminate", E), ("eliminate", C), ("fill", D), ("fill", B)])
self.assertEqual(log[0][2], [9, 2, 4, 3, 2])
self.assertEqual(log[1][2], [None, 5, 4, 3, 2])
self.assertEqual(log[2][2], [None, 5, 4, 5, None])
self.assertEqual(log[3][2], [None, 5, None, 9, None])
def test_hare_gives_the_same_set(self):
self.assertEqual(set(single_transferable_vote(EXAMPLE, 5, 3, "hare")), {A, B, D})
def test_first_preferences_alone_pick_another_set(self):
firsts = [sum(1 for r in EXAMPLE if r[0] == a) for a in range(5)]
top3 = sorted(range(5), key=lambda a: (-firsts[a], a))[:3]
self.assertEqual(set(top3), {A, C, D})
class TestAgainstRecount(unittest.TestCase):
def test_random_profiles(self):
rng = random.Random(11)
for _ in range(600):
m = rng.randint(1, 5)
n = rng.randint(1, 12)
k = rng.randint(1, m)
prof = random_ballots(rng, m, n, rng.random() < 0.5)
for quota in ("droop", "hare"):
self.assertEqual(single_transferable_vote(prof, m, k, quota), recount_stv(prof, m, k, quota))
def test_elect_entries_reach_the_quota(self):
rng = random.Random(12)
for _ in range(300):
m = rng.randint(2, 5)
n = rng.randint(2, 15)
k = rng.randint(1, m)
prof = random_ballots(rng, m, n, True)
v = sum(1 for r in prof if r)
if v == 0:
continue
q = droop_quota(v, k)
winners, log = stv_count(prof, m, k)
self.assertEqual(len(winners), k)
self.assertEqual(len(set(winners)), k)
for act, c, t in log:
if act == "elect":
self.assertGreaterEqual(t[c], q)
self.assertEqual(t[c], max(x for x in t if x is not None))
class TestOneSeat(unittest.TestCase):
def test_k1_is_instant_runoff(self):
rng = random.Random(13)
for _ in range(500):
m = rng.randint(1, 5)
n = rng.randint(1, 11)
prof = random_ballots(rng, m, n, rng.random() < 0.5)
if not any(prof):
continue
self.assertEqual(single_transferable_vote(prof, m, 1), [irv_to_the_end(prof, m)])
def test_not_monotone(self):
before = [(A, B, C)] * 6 + [(B, A, C)] * 2 + [(B, C, A)] * 4 + [(C, A, B)] * 5
after = [(A, B, C)] * 8 + [(B, C, A)] * 4 + [(C, A, B)] * 5
self.assertEqual(single_transferable_vote(before, 3, 1), [A])
self.assertEqual(single_transferable_vote(after, 3, 1), [C])
class TestProportionality(unittest.TestCase):
def check(self, prof, m, k, quota):
v = sum(1 for r in prof if r)
q = droop_quota(v, k) if quota == "droop" else hare_quota(v, k)
W = set(single_transferable_vote(prof, m, k, quota))
for S, j in solid_coalitions(prof, m, q):
self.assertGreaterEqual(len(W & S), min(j, k, len(S)))
def test_planted_coalitions(self):
rng = random.Random(14)
for _ in range(300):
m = rng.randint(2, 5)
k = rng.randint(1, m)
size = rng.randint(1, m)
S = rng.sample(range(m), size)
prof = random_ballots(rng, m, rng.randint(0, 8), True)
for _ in range(rng.randint(1, 10)):
head = S[:]
rng.shuffle(head)
tail = [a for a in range(m) if a not in S]
rng.shuffle(tail)
prof.append(tuple(head + tail[: rng.randint(0, len(tail))]))
rng.shuffle(prof)
for quota in ("droop", "hare"):
self.check(prof, m, k, quota)
def test_all_profiles_of_four_voters(self):
rankings = all_rankings(3)
for p in combinations(rankings * 4, 4):
for k in (1, 2):
self.check(list(p), 3, k, "droop")
class TestQuotaChoice(unittest.TestCase):
def test_droop_and_hare_differ(self):
prof = [(0, 1, 3, 2), (0, 3, 1, 2), (1, 0, 3, 2), (2, 0, 3, 1)] + [(2, 1, 0, 3)] * 2 + [(2, 1, 3, 0)] * 2
self.assertEqual(single_transferable_vote(prof, 4, 2), [2, 1])
self.assertEqual(single_transferable_vote(prof, 4, 2, "hare"), [2, 0])
self.assertEqual(single_transferable_vote(prof, 4, 1), [2])
class TestEdgeCases(unittest.TestCase):
def test_more_seats_than_candidates(self):
self.assertEqual(single_transferable_vote([(1, 0), (1,)], 2, 3), [1, 0])
def test_empty_ballots_are_ignored(self):
prof = [(), (0,), (1, 0), (1,), ()]
self.assertEqual(single_transferable_vote(prof, 2, 1), [1])
def test_anonymity(self):
rng = random.Random(15)
sample = [random_profile(rng, 4, rng.randint(2, 9)) for _ in range(200)]
rule = lambda P, m: frozenset(single_transferable_vote(P, m, 2))
self.assertIsNone(check_anonymity(rule, 4, None, profiles=sample))
if __name__ == "__main__":
unittest.main()
History
Carl Andrae proposed a rule of this kind in Denmark in 1855, and Thomas Hare published his in Britain in 1857 and 1859, with the quota . Henry Droop (1881) argued for the smaller quota now named after him. The transfer of surpluses at a fraction of their value is named after J. B. Gregory. STV elects the parliaments of Ireland and Malta and the Australian Senate, and Scottish local councils since 2007. Dummett (1984) named the property of proportionality for solid coalitions, and Tideman (1995) surveys the rules and their variants. Bartholdi and Orlin (1991) showed that manipulating the count is NP-complete.
References
- Nicolaus Tideman, The single transferable vote, Journal of Economic Perspectives 9(1) (1995), 27-38, the rules of the count, the quotas and the transfer of surpluses; footnote 1 for proportionality for solid coalitions, after Dummett (1984)
- H. R. Droop, On methods of electing representatives, Journal of the Statistical Society of London 44(2) (1881), 141-202, the argument for the quota that carries his name
- 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 rule
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 CH8C0N Edit this page History Report an error Markdown