Algorithm Search⌘K

Algorithmintro

Approval voting

Also called approval ballot.

Each voter approves any set of candidates, and the candidate with the most approvals wins.

Time
O(n + m + L) worst
Space
O(m) extra
Where
L = the total number of approvals on all ballots; m = the number of candidates; n = the number of voters
Properties
not comparison baseddeterministiciterative
Origin
Steven J. Brams, Peter C. Fishburn, 1978

Approval voting is a single-winner voting rule in which each voter approves any set of candidates and the candidate with the most approvals wins. The ballot is a set, not a ranking, so the rule sits between plurality voting, where each voter approves exactly one candidate, and the rules that read a full preference profile. The count is one pass over the ballots, and the rule is anonymous, neutral, monotone and consistent. Its main strength is strategic: a voter who only separates good candidates from bad ones can never gain by a false ballot.

In plain words

Each voter marks every candidate that they find acceptable, one or many. A mark counts once, and the candidate with the most marks wins. A voter who likes two similar candidates can mark both, so the two do not split the votes of their supporters as they do under plurality. The hard choice for a voter is where to put the line: marking a second choice helps it against worse candidates, but it can also help it beat the first choice.

The problem

There are mm candidates A={0,…,m−1}A = \{0, \ldots, m - 1\} and nn voters. Voter ii casts a ballot Si⊆AS_i \subseteq A, the set of candidates that voter ii approves; the empty ballot and the full ballot are allowed. The input is the approval profile (S1,…,Sn)(S_1, \ldots, S_n), and the output is one winner. The approval score of a candidate aa is

s(a)=∣{i:a∈Si}∣,s(a) = |\{ i : a \in S_i \}|,

the approval correspondence returns W=arg⁡max⁡as(a)W = \arg\max_a s(a), and the resolute rule returns the smallest index in WW, the fixed tie-breaking rule of this area.

When the voters also have rankings, a ballot SS is called sincere for a ranking rr if every approved candidate is ranked above every candidate that is not approved, that is, if SS is a set of the top kk candidates of rr for some kk. The model of voter behaviour is then part of the rule: the same rankings can give different winners for different choices of kk.

The algorithm

  1. APPROVAL(S_1, ..., S_n, m) ▷ each S_i is a set of candidates
  2. 1s[a] ← 0 for each candidate a = 0, ..., m - 1
  3. 2for each ballot S in S_1, ..., S_n do
  4. 3for each candidate a in S do
  5. 4s[a] ← s[a] + 1
  6. 5best ← max over a of s[a]
  7. 6W ← {a : s[a] = best} ▷ the approval correspondence
  8. 7return the smallest candidate in W ▷ the fixed tie-breaking rule

Lines L1 to L4 count, for each candidate, the ballots that contain it. Lines L5 and L6 find all candidates with the highest count, and line L7 applies the tie-breaking rule. The code also returns WW from a separate function, because the resolute rule with a tie-break by index is not neutral, while the correspondence is.

Example

Take the nine voters of the plurality voting page and let each approve the candidates before the bar: 4 voters with ranking a≻b≻ca \succ b \succ c approve {a}\{a\}, 3 voters with ranking b≻c≻ab \succ c \succ a approve {b}\{b\}, and 2 voters with ranking c≻b≻ac \succ b \succ a approve {c,b}\{c, b\}.

step state
L1 s=(0,0,0)s = (0, 0, 0)
L2 to L4, the 4 ballots {a}\{a\} s=(4,0,0)s = (4, 0, 0)
L2 to L4, the 3 ballots {b}\{b\} s=(4,3,0)s = (4, 3, 0)
L2 to L4, the 2 ballots {c,b}\{c, b\} s=(4,5,2)s = (4, 5, 2)
L5 and L6 best=5best = 5, W={b}W = \{b\}
L7 return bb

Plurality elects aa on these voters, which is the Condorcet loser, while approval elects bb, the Condorcet winner. The two cc-voters did not have to desert cc to help bb.

Approval voting is still not Condorcet consistent. Let 3 voters with ranking a≻b≻ca \succ b \succ c approve {a,b}\{a, b\} and 2 voters with ranking b≻a≻cb \succ a \succ c approve {b}\{b\}. Then s=(3,5,0)s = (3, 5, 0) and bb wins, but aa beats bb on 3 of the 5 rankings and is the Condorcet winner. If the three aa-voters approve only {a}\{a\}, then aa wins by 3 to 2. Both ballots are sincere for these voters, and the result depends on where they put the line.

Correctness

After the loop has read the first kk ballots, s[a]s[a] is the number of these ballots that contain aa, for every aa. This loop invariant holds for k=0k = 0 by line L1, and the inner loop of lines L3 and L4 adds 1 to the counter of each member of the new ballot and to no other counter. At the end s[a]=s(a)s[a] = s(a), line L6 builds WW, and line L7 returns its smallest element. The proof in proofs/correctness.md also proves the properties below.

Proof: Correctness and properties of approval votingfull

Let A={0,…,m−1}A = \{0, \ldots, m - 1\} with m≥1m \ge 1 and let (S1,…,Sn)(S_1, \ldots, S_n) be an approval profile, with Si⊆AS_i \subseteq A. Write F(a)={i:a∈Si}F(a) = \{ i : a \in S_i \} for the voters who approve aa, s(a)=∣F(a)∣s(a) = |F(a)| for the approval score, W={a:s(a)=max⁡bs(b)}W = \{ a : s(a) = \max_b s(b) \} for the approval correspondence, and f=min⁡Wf = \min W for the resolute rule.

Claim 1 (correctness). APPROVAL returns ff.

Proof. Invariant of the outer loop of line L2: after the first kk ballots, s[a]=∣{i≤k:a∈Si}∣s[a] = |\{ i \le k : a \in S_i \}| for every aa. For k=0k = 0 this is line L1. The pass for ballot k+1k + 1 runs lines L3 and L4 once for each member of Sk+1S_{k+1}, since a set has no repeated members, so it adds 1 to s[a]s[a] exactly when a∈Sk+1a \in S_{k+1}. That keeps the invariant. After nn passes, s[a]=s(a)s[a] = s(a). Line L5 computes the maximum of the finite nonempty list, line L6 builds W≠∅W \ne \emptyset, and line L7 returns min⁡W=f\min W = f.

Claim 2 (anonymity and neutrality). Permuting the voters leaves WW and ff unchanged. If every ballot is renamed by a permutation π\pi of AA, then WW becomes π(W)\pi(W).

Proof. s(a)s(a) counts ballots and does not depend on their order. Under the renaming, π(a)\pi(a) is in the renamed ballot ii exactly when a∈Sia \in S_i, so the new score of π(a)\pi(a) is s(a)s(a), and the maximizers are renamed by π\pi.

Claim 3 (Pareto). If F(b)⊊F(a)F(b) \subsetneq F(a), then b∉Wb \notin W.

Proof. s(b)=∣F(b)∣<∣F(a)∣=s(a)≤max⁡ss(b) = |F(b)| < |F(a)| = s(a) \le \max s.

Claim 4 (monotonicity). If w=fw = f and w∉Siw \notin S_i, then for the profile with SiS_i replaced by Si∪{w}S_i \cup \{w\} the winner is still ww.

Proof. The score of ww goes up by 1 and no other score changes. Before the change, s(w)≥s(c)s(w) \ge s(c) for every cc and s(w)>s(c)s(w) > s(c) for every c<wc < w. Both inequalities stay true and the first becomes strict, so ww is the unique maximizer.

Claim 5 (consistency). For approval profiles P1P_1 and P2P_2 of disjoint groups, if W(P1)∩W(P2)≠∅W(P_1) \cap W(P_2) \ne \emptyset, then W(P1+P2)=W(P1)∩W(P2)W(P_1 + P_2) = W(P_1) \cap W(P_2).

Proof. The scores add, sP1+P2=sP1+sP2s_{P_1 + P_2} = s_{P_1} + s_{P_2}. Each joined score is at most max⁡sP1+max⁡sP2\max s_{P_1} + \max s_{P_2}, with equality exactly for the members of W(P1)∩W(P2)W(P_1) \cap W(P_2). That set is not empty, so the bound is the joined maximum and its maximizers are this set.

Claim 6 (dominance of the sincere ballot for dichotomous preferences). Let a voter have a set G⊆AG \subseteq A of good candidates and only care whether the winner is in GG. Fix the ballots of the other voters. If the voter casts SS and the winner fSf_S is in GG, then with the ballot GG the winner fGf_G is in GG too.

Proof. Let tt be the scores of the other voters alone. With ballot TT the score of aa is t(a)+[a∈T]t(a) + [a \in T]. Order the candidates by the key (score,−index)(\text{score}, -\text{index}); the winner is the unique candidate with the largest key. Suppose fG=x∉Gf_G = x \notin G. Then the key of xx with ballot GG is larger than the key of every g∈Gg \in G. Change the ballot from GG to any SS. The score of each g∈Gg \in G does not go up, since g∈Gg \in G already gave it the point, and the score of xx does not go down, since x∉Gx \notin G had no point from the voter. So the key of xx is still larger than the key of every g∈Gg \in G, and the winner fSf_S is not in GG. By contraposition, fS∈Gf_S \in G implies fG∈Gf_G \in G.

So the ballot GG is a dominant strategy for this voter. It is also sincere, since it approves exactly the good candidates.

Claim 7 (plurality ballots). If ∣Si∣=1|S_i| = 1 for every ii, the winner is the plurality winner of any profile of rankings whose tops are the approved candidates.

Proof. Then s(a)s(a) is the number of voters whose single approved candidate, the top of their ranking, is aa. This is the plurality score, and both rules break ties by the smallest index.

Claim 8 (time). APPROVAL runs in O(n+m+L)O(n + m + L) time with L=∑i∣Si∣L = \sum_i |S_i|, and in O(m)O(m) extra space.

Proof. Line L1 costs O(m)O(m). The outer loop does nn iterations, and the inner loop does ∣Si∣|S_i| unit-cost updates in iteration ii, so the loops cost O(n+L)O(n + L). Lines L5 to L7 scan mm counters. Only the counters and WW are stored. ■\blacksquare

Complexity

Line L1 takes O(m)O(m) time. The outer loop runs nn times, and the inner loop runs once per approval, so lines L2 to L4 take O(n+L)O(n + L) time, where L=∑i∣Si∣≤nmL = \sum_i |S_i| \le n m. Lines L5 to L7 take O(m)O(m) time. The total is O(n+m+L)O(n + m + L) in the word RAM model, and the extra space is the mm counters. If ballots are stored as bit vectors of length mm, the scan costs O(nm)O(n m) instead.

Properties

The proofs are in proofs/correctness.md, and the tests check each one by brute force over all approval profiles with 3 or 4 candidates and 2 or 3 voters.

  • Anonymous and neutral as a correspondence. The resolute rule is not neutral, because of the tie-break by index.
  • Pareto, in the approval sense. If the voters who approve bb form a strict subset of the voters who approve aa, then s(b)<s(a)s(b) < s(a) and bb does not win.
  • Monotone. Adding the winner to one more ballot keeps it the winner.
  • Consistent. If two disjoint groups have winner sets with a common member, the joined group elects exactly the common members, because the scores add.
  • Sincere voting is dominant for dichotomous preferences. A voter who only cares whether the winner is in a set GG cannot do better than the ballot GG, whatever the other voters do (Brams and Fishburn 1978). This holds with the fixed tie-break too.
  • No dominant ballot for general preferences. With 3 candidates and a ranking a≻b≻ca \succ b \succ c, the only ballots that no other ballot dominates are {a}\{a\} and {a,b}\{a, b\}, and neither one dominates the other. With 4 candidates the insincere ballot {a,c}\{a, c\} is also undominated. This agrees with Gibbard's theorem for general game forms, of which the Gibbard-Satterthwaite theorem is the special case for ranking ballots.
  • Not Condorcet consistent, as the second example shows.
  • Plurality as a special case. If every voter approves exactly one candidate, approval voting is plurality voting.

Variants and improvements

  • kk-approval. Each voter must approve exactly kk candidates. This is a scoring rule on rankings and loses the free choice of the line.
  • Score and range voting. Each voter gives every candidate a grade from a fixed scale, and the highest total or mean wins. Approval voting is the case of two grades.
  • Satisfaction approval voting. A ballot that approves kk candidates gives 1/k1/k to each, so every voter has the same total weight.
  • Multiwinner forms. To elect a committee of kk members from approval ballots, proportional approval voting and the rules studied under justified representation give groups of voters a fair share of the seats. Taking the kk candidates with the most approvals does not.
  • Fallback and runoff forms. An approval round can pick the top two for a runoff, as in the two-round system of plurality voting.

When to use it

Use approval voting for a single winner when ballots must stay simple, there are several similar candidates, and vote splitting would harm the result under plurality voting. It suits committees, societies and straw polls in which voters can tell acceptable from unacceptable candidates. If voters have strong rankings and you want a pairwise majority winner, use a Condorcet method such as the Copeland method or ranked pairs. If you want a majority of the remaining ballots in a last round, use instant-runoff voting.

Pitfalls

  • Counting an approval twice. Store each ballot as a set. A list that repeats a candidate gives that candidate an extra point.
  • Reading a ranking as an approval ballot. A ranking says nothing about where the line is. Converting rankings into ballots needs an explicit threshold, and the result depends on it, as the second example shows.
  • Taking the top kk for a committee. With kk seats, the kk candidates with the most approvals can all come from one majority group, and a large minority gets nothing.
  • Bullet voting. Voters who fear that a second approval will beat their first choice approve one candidate only. If most voters do this, the rule is plurality again.

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.

agtprefs.pyI0RawGitHub
# 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))
approval_voting.py 39 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/approval-voting/. The authors are listed in prov/2YTCNT.jsonl.

from typing import AbstractSet, Sequence

Ballot = AbstractSet[int]


def approval_scores(ballots: Sequence[Ballot], m: int) -> list[int]:
    """Return s with s[a] the number of ballots that approve candidate a.

    The candidates are 0, ..., m - 1 and each ballot is a set of candidates. The time is
    O(n + m + L), with L the total size of the n ballots.
    """
    s = [0] * m  # @line L1
    for S in ballots:  # @line L2
        for a in S:  # @line L3
            s[a] += 1  # @line L4
    return s


def approval_winners(ballots: Sequence[Ballot], m: int) -> frozenset[int]:
    """Return the set of candidates with the most approvals (the approval correspondence)."""
    s = approval_scores(ballots, m)
    best = max(s)  # @line L5
    return frozenset(a for a in range(m) if s[a] == best)  # @line L6


def approval(ballots: Sequence[Ballot], m: int) -> int:
    """Return the approval winner; a tie goes to the candidate with the smallest index.

    Precondition: m >= 1. Empty ballots are allowed. Time O(n + m + L), extra space O(m).
    """
    return min(approval_winners(ballots, m))  # @line L7


def sincere_ballot(ranking: Sequence[int], k: int) -> frozenset[int]:
    """Return the ballot that approves the k best candidates of the ranking."""
    return frozenset(ranking[:k])
test_approval_voting.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/approval-voting/. The authors are listed in prov/2YTCNT.jsonl.

import itertools
import random
from collections import Counter

from agtprefs import (all_profiles, check_anonymity, check_condorcet_consistency,
                      check_neutrality, condorcet_winner, permute_profile, random_approval_profile,
                      random_profile)
from approval_voting import approval, approval_scores, approval_winners, sincere_ballot

A, B, C, D = 0, 1, 2, 3


def all_ballots(m):
    """Every subset of the m candidates, from the empty ballot to the full one."""
    return [frozenset(c) for k in range(m + 1) for c in itertools.combinations(range(m), k)]


def all_approval_profiles(m, n):
    return itertools.product(all_ballots(m), repeat=n)


def place(r, a):
    return r.index(a)


# The worked example: the voters of the plurality page, each approving the candidates above
# the line: 4 voters a | b c, 3 voters b | c a and 2 voters c b | a.
EXAMPLE = (frozenset({A}),) * 4 + (frozenset({B}),) * 3 + (frozenset({C, B}),) * 2


def test_worked_example():
    assert approval_scores(EXAMPLE, 3) == [4, 5, 2]
    assert approval(EXAMPLE, 3) == B
    # Plurality on the same voters elects a; approval finds the Condorcet winner b.
    rankings = ((A, B, C),) * 4 + ((B, C, A),) * 3 + ((C, B, A),) * 2
    assert condorcet_winner(rankings, 3) == B


def test_condorcet_winner_can_lose():
    # 3 voters a > b > c approve {a, b}; 2 voters b > a > c approve {b}. a is the Condorcet
    # winner, but b has 5 approvals to 3.
    rankings = ((A, B, C),) * 3 + ((B, A, C),) * 2
    ballots = (frozenset({A, B}),) * 3 + (frozenset({B}),) * 2
    assert condorcet_winner(rankings, 3) == A
    assert approval_scores(ballots, 3) == [3, 5, 0]
    assert approval(ballots, 3) == B
    # If the three a-voters approve only a, then a wins 3 to 2.
    narrow = (frozenset({A}),) * 3 + (frozenset({B}),) * 2
    assert approval(narrow, 3) == A


def test_matches_counter_on_random_profiles():
    rng = random.Random(31)
    for _ in range(2000):
        m, n = rng.randint(1, 6), rng.randint(0, 12)
        P = random_approval_profile(rng, m, n, rng.random())
        cnt = Counter(a for S in P for a in S)
        s = approval_scores(P, m)
        assert s == [cnt[a] for a in range(m)]
        assert sum(s) == sum(len(S) for S in P)
        W = {a for a in range(m) if cnt[a] == max(s)}
        assert approval_winners(P, m) == W
        assert approval(P, m) == min(W)


def test_edge_cases():
    assert approval((), 3) == 0 and approval_winners((), 3) == {0, 1, 2}
    assert approval((frozenset(),) * 4, 2) == 0
    assert approval((frozenset({1, 2}), frozenset({2, 1})), 3) == 1
    assert approval_winners((frozenset({0, 1, 2}),), 3) == {0, 1, 2}


def test_plurality_ballots_give_plurality():
    # If every voter approves exactly one candidate, approval voting is plurality voting.
    rng = random.Random(32)
    for _ in range(500):
        m, n = rng.randint(1, 5), rng.randint(1, 9)
        P = random_profile(rng, m, n)
        tops = Counter(r[0] for r in P)
        best = max(tops[a] for a in range(m))
        assert approval([sincere_ballot(r, 1) for r in P], m) == min(
            a for a in range(m) if tops[a] == best)


def test_axioms_by_brute_force():
    for m, n in [(3, 2), (3, 3), (4, 2)]:
        domain = list(all_approval_profiles(m, n))
        assert check_anonymity(approval, m, n, profiles=domain) is None
        assert check_neutrality(approval_winners, m, n, profiles=domain) is None
        for P in domain:
            W = approval_winners(P, m)
            # Pareto: if the voters who approve b are a strict subset of those who approve a,
            # then b does not win.
            for a, b in itertools.permutations(range(m), 2):
                fa = {i for i, S in enumerate(P) if a in S}
                fb = {i for i, S in enumerate(P) if b in S}
                if fb < fa:
                    assert b not in W
            # Monotonicity: one more approval for a winner keeps it a winner, and the resolute
            # winner stays the winner.
            w = approval(P, m)
            for i, S in enumerate(P):
                if w not in S:
                    Q = P[:i] + (S | {w},) + P[i + 1:]
                    assert approval(Q, m) == w
    # The resolute rule with the fixed tie-break is not neutral.
    P = (frozenset({A}), frozenset({B}))
    assert approval(permute_profile(P, (1, 0, 2)), 3) != 1


def test_consistency_by_brute_force():
    for n1, n2 in [(1, 1), (1, 2), (2, 2)]:
        checked = 0
        for P1 in all_approval_profiles(3, n1):
            W1 = approval_winners(P1, 3)
            for P2 in all_approval_profiles(3, n2):
                both = W1 & approval_winners(P2, 3)
                if both:
                    assert approval_winners(P1 + P2, 3) == both
                    checked += 1
        assert checked > 0


def test_sincere_ballot_is_dominant_for_dichotomous_preferences():
    # A voter who only cares whether the winner is in the set G cannot gain by any ballot
    # other than G, whatever the other voters do, with the fixed tie-break too.
    for m, others in [(3, 1), (3, 2), (3, 3), (4, 2)]:
        ballots = all_ballots(m)
        for O in all_approval_profiles(m, others):
            winner = {S: approval((S,) + O, m) for S in ballots}
            for G in ballots:
                if winner[G] not in G:
                    assert not any(winner[S] in G for S in ballots)


def undominated_ballots(r, m, others):
    """Ballots that no other ballot weakly dominates, for a voter with ranking r."""
    ballots = all_ballots(m)
    rows = list(all_approval_profiles(m, others))
    res = {S: [place(r, approval((S,) + O, m)) for O in rows] for S in ballots}
    keep = []
    for S in ballots:
        dominated = any(
            all(t <= s for s, t in zip(res[S], res[T])) and res[T] != res[S]
            for T in ballots if T != S)
        if not dominated:
            keep.append(tuple(sorted(S)))
    return sorted(keep)


def test_admissible_ballots_of_brams_and_fishburn():
    # With 3 candidates and a ranking a > b > c, only {a} and {a, b} are undominated, and
    # neither dominates the other, so there is no dominant ballot. With 4 candidates the
    # insincere ballot {a, c} is undominated too.
    assert undominated_ballots((A, B, C), 3, 2) == [(A,), (A, B)]
    assert undominated_ballots((A, B, C, D), 4, 2) == [(A,), (A, B), (A, B, C), (A, C)]


def test_not_condorcet_consistent_with_sincere_thresholds():
    # Voters who approve their top half (rounded up) can still miss the Condorcet winner.
    def top_half(P, m):
        return approval([sincere_ballot(r, (m + 1) // 2) for r in P], m)

    P, c = check_condorcet_consistency(top_half, 3, 3)
    assert top_half(P, 3) != c
    assert any(condorcet_winner(P, 3) is not None for P in all_profiles(3, 3))

History

Several authors studied approval voting in the 1970s, and Brams and Fishburn (1978) gave the first full analysis of its strategic properties. Scientific societies such as the Mathematical Association of America and the Institute of Electrical and Electronics Engineers took it up for their elections in the following years, and some of them, the IEEE among them, later dropped it; Brams and Fishburn (2005) review this record. In public elections, Fargo, North Dakota, adopted approval voting for city elections by a referendum in 2018, and St. Louis adopted it for the primary round of its city elections in 2020.

References

  1. Steven J. Brams and Peter C. Fishburn, Approval voting, American Political Science Review 72(3) (1978), 831-847, the definition, the admissible and sincere strategies, and the dominance of sincere voting for dichotomous preferences
  2. Steven J. Brams and Peter C. Fishburn, Going from theory to practice: the mixed success of approval voting, Social Choice and Welfare 25(2-3) (2005), 457-474, the use of approval voting by scientific societies and the reasons some of them dropped it
  3. 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)

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example