Algorithm Search⌘K

Algorithmintro

Plurality voting

Also called first past the post, relative majority.

Elects the candidate ranked first by the most voters. It ignores all but the top choice of each voter.

Time
O(n + m) worst
Space
O(m) extra
Where
m = the number of candidates; n = the number of voters
Properties
not comparison baseddeterministiciterative
Origin
Jean Charles de Borda, Allan Gibbard, Mark Satterthwaite, 1784

Plurality voting elects the candidate that the most voters rank first. It reads only the top entry of each ballot in a preference profile, counts the first places of each candidate, and breaks a tie by a fixed rule. It is the rule of most single-member elections in the United Kingdom, the United States, Canada and India, where it is called "first past the post". It is the fastest rule there is, but it can elect a candidate that a majority of the voters ranks last, and it rewards voters who do not vote for their true first choice.

In plain words

Each voter names one favourite. The candidate with the most votes wins, even when that is far less than half of the votes. A ballot says nothing about the second choice, so the rule cannot see that most voters may dislike the winner. When two similar candidates split the votes of their supporters, a third candidate that most voters like less can win. Voters know this, so many of them vote for the strongest candidate they can accept, and not for the one they like best.

The problem

There are mm candidates A={0,…,m−1}A = \{0, \ldots, m - 1\} and nn voters. Voter ii has a ranking rir_i of all candidates, a tuple with the best candidate first, and the input is the profile P=(r1,…,rn)P = (r_1, \ldots, r_n). The output is one winner in AA. The plurality score of a candidate aa is

sP(a)=∣{i:ri[1]=a}∣,s_P(a) = |\{ i : r_i[1] = a \}|,

the number of voters who rank aa first. The plurality correspondence returns the set W(P)=arg⁡max⁡asP(a)W(P) = \arg\max_a s_P(a), and the resolute rule returns one element of it. Ties go to the candidate with the smallest index, as on every rule page of this area. In practice a ballot names only one candidate, and the code needs only that entry.

The algorithm

  1. PLURALITY(P, m) ▷ P = (r_1, ..., r_n), each ranking best first
  2. 1s[a] ← 0 for each candidate a = 0, ..., m - 1
  3. 2for each ranking r in P do
  4. 3s[r[1]] ← s[r[1]] + 1 ▷ only the top entry is read
  5. 4best ← max over a of s[a]
  6. 5W ← {a : s[a] = best} ▷ the plurality correspondence
  7. 6return the smallest candidate in W ▷ the fixed tie-breaking rule

Lines L1 to L3 are a counting pass: one counter per candidate, and one increment per voter. Lines L4 and L5 find all candidates with the highest count. Line L6 applies the tie-breaking rule. The code returns WW from a separate function, because the properties of the rule are cleaner on the correspondence: the tie-break by index favours candidate 0, so the resolute rule is not neutral, while the correspondence is.

Example

Take three candidates a,b,ca, b, c (indices 0, 1, 2) and nine voters:

voters ranking
4 a≻b≻ca \succ b \succ c
3 b≻c≻ab \succ c \succ a
2 c≻b≻ac \succ b \succ a
step state
L1 s=(0,0,0)s = (0, 0, 0)
L2 to L3, the 4 voters a≻b≻ca \succ b \succ c s=(4,0,0)s = (4, 0, 0)
L2 to L3, the 3 voters b≻c≻ab \succ c \succ a s=(4,3,0)s = (4, 3, 0)
L2 to L3, the 2 voters c≻b≻ac \succ b \succ a s=(4,3,2)s = (4, 3, 2)
L4 and L5 best=4best = 4, W={a}W = \{a\}
L6 return aa

The winner aa has 4 of the 9 votes, less than half. The pairwise counts show what the ballots hide: bb beats aa by 5 to 4 and beats cc by 7 to 2, so bb is the Condorcet winner, and aa loses to both bb and cc by 5 to 4, so aa is the Condorcet loser. The Borda count gives aa, bb and cc the scores 8, 12 and 7, and instant-runoff voting removes cc and then elects bb by 5 to 4. The two voters c≻b≻ac \succ b \succ a can change the result: if they report b≻c≻ab \succ c \succ a, the scores become (4,5,0)(4, 5, 0) and bb wins, which they prefer to aa.

With three candidates, a Condorcet loser can win alone, with no tie, only when there are 7 or more voters; the smallest case is 3 voters a≻b≻ca \succ b \succ c, 2 voters b≻c≻ab \succ c \succ a and 2 voters c≻b≻ac \succ b \succ a. With the tie-break, 3 voters suffice: the ballots a≻b≻ca \succ b \succ c, b≻c≻ab \succ c \succ a and c≻b≻ac \succ b \succ a give one first place to each candidate, and the tie goes to aa, which loses to bb and to cc by 2 to 1.

Correctness

After the loop of lines L2 and L3 has read the first kk ballots, s[a]s[a] is the number of these ballots with aa on top, for every aa. This loop invariant holds at the start, where all counters are 0, and each pass adds 1 to exactly one counter, the one of the top of the new ballot. At the end s[a]=sP(a)s[a] = s_P(a), so line L5 builds W(P)W(P) and line L6 returns its smallest element. The proof in proofs/correctness.md also proves the properties below.

Proof: Correctness and properties of plurality votingfull

Let A={0,…,m−1}A = \{0, \ldots, m - 1\} with m≥1m \ge 1, and let P=(r1,…,rn)P = (r_1, \ldots, r_n) be a profile of rankings, each best first. Write sP(a)=∣{i:ri[1]=a}∣s_P(a) = |\{ i : r_i[1] = a \}| for the plurality score and W(P)={a:sP(a)=max⁡bsP(b)}W(P) = \{ a : s_P(a) = \max_b s_P(b) \} for the plurality correspondence. The resolute rule is f(P)=min⁡W(P)f(P) = \min W(P).

Claim 1 (correctness). PLURALITY returns f(P)f(P).

Proof. Invariant of the loop of lines L2 and L3: after the first kk ballots, s[a]=∣{i≤k:ri[1]=a}∣s[a] = |\{ i \le k : r_i[1] = a \}| for every aa. For k=0k = 0 this is line L1. If it holds for kk, the pass for ballot k+1k + 1 adds 1 to s[rk+1[1]]s[r_{k+1}[1]] and to no other counter, and the set on the right gains the index k+1k + 1 for a=rk+1[1]a = r_{k+1}[1] only, so it holds for k+1k + 1. After nn passes, s[a]=sP(a)s[a] = s_P(a). Line L4 sets best=max⁡asP(a)best = \max_a s_P(a), line L5 builds W(P)W(P), which is nonempty because a maximum is attained on the finite nonempty set AA, and line L6 returns min⁡W(P)=f(P)\min W(P) = f(P).

Claim 2 (anonymity). For every permutation σ\sigma of the voters, W(rσ(1),…,rσ(n))=W(P)W(r_{\sigma(1)}, \ldots, r_{\sigma(n)}) = W(P), and so ff is the same on both profiles.

Proof. sP(a)s_P(a) counts a set of ballots with a property that depends only on the ballot, so it does not depend on the order of the voters.

Claim 3 (neutrality of the correspondence). For a permutation π\pi of AA, let πP\pi P be the profile in which every ranking has each aa replaced by π(a)\pi(a). Then W(πP)=π(W(P))W(\pi P) = \pi(W(P)).

Proof. The top of the renamed ballot πri\pi r_i is π(ri[1])\pi(r_i[1]), so sπP(π(a))=sP(a)s_{\pi P}(\pi(a)) = s_P(a) for every aa. The two score vectors have the same maximum, and π(a)\pi(a) attains it in πP\pi P exactly when aa attains it in PP.

The resolute rule is not neutral when m≥2m \ge 2: for the profile P=((0,1,…),(1,0,…))P = ((0, 1, \ldots), (1, 0, \ldots)) and π\pi the swap of 0 and 1, πP\pi P has the same two ballots in the other order, so f(πP)=0≠1=π(f(P))f(\pi P) = 0 \ne 1 = \pi(f(P)).

Claim 4 (Pareto). If n≥1n \ge 1 and every voter ranks aa above bb, then b∉W(P)b \notin W(P).

Proof. No ballot has bb on top, so sP(b)=0s_P(b) = 0. The scores add up to n≥1n \ge 1, so some candidate has a positive score, and max⁡csP(c)>0=sP(b)\max_c s_P(c) > 0 = s_P(b).

Claim 5 (monotonicity). Let w∈W(P)w \in W(P), and let QQ be PP with one ballot rir_i changed by moving ww up one place and keeping the order of all other candidates. Then w∈W(Q)w \in W(Q), and if w=f(P)w = f(P) then w=f(Q)w = f(Q).

Proof. If ww is not in second place in rir_i, the top of rir_i does not change, and sQ=sPs_Q = s_P. If ww is in second place, the old top tt loses one first place and ww gains one: sQ(w)=sP(w)+1s_Q(w) = s_P(w) + 1, sQ(t)=sP(t)−1s_Q(t) = s_P(t) - 1, and every other score is the same. In both cases sQ(w)≥sQ(c)s_Q(w) \ge s_Q(c) for every cc, because sQ(w)≥sP(w)≥sP(c)≥sQ(c)s_Q(w) \ge s_P(w) \ge s_P(c) \ge s_Q(c). So w∈W(Q)w \in W(Q). Moreover W(Q)⊆W(P)W(Q) \subseteq W(P): a candidate c≠wc \ne w in W(Q)W(Q) has sP(c)≥sQ(c)=sQ(w)≥sP(w)=max⁡sPs_P(c) \ge s_Q(c) = s_Q(w) \ge s_P(w) = \max s_P. So if ww is the smallest element of W(P)W(P), it is also the smallest element of W(Q)W(Q). Any raise of ww that keeps the order of the other candidates is a chain of such one-place moves, so the claim holds for it too.

Claim 6 (consistency). Let P1P_1 and P2P_2 be profiles of disjoint groups of voters, and let P1+P2P_1 + P_2 be the joined profile. 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}. Let Mj=max⁡sPjM_j = \max s_{P_j}. Every candidate has a joined score at most M1+M2M_1 + M_2, and a candidate attains this bound exactly when it attains M1M_1 in P1P_1 and M2M_2 in P2P_2, that is, when it is in W(P1)∩W(P2)W(P_1) \cap W(P_2). That set is nonempty, so M1+M2M_1 + M_2 is the maximum of the joined scores and W(P1+P2)=W(P1)∩W(P2)W(P_1 + P_2) = W(P_1) \cap W(P_2).

Claim 7 (two candidates). If m=2m = 2, then f(P)=0f(P) = 0 exactly when 2sP(0)≥n2 s_P(0) \ge n; that is, ff is majority rule with ties to candidate 0, and ff elects the Condorcet winner whenever there is one.

Proof. With two candidates the top of a ballot is the candidate preferred to the other one, so sP(0)=nP(0,1)s_P(0) = n_P(0, 1) and sP(1)=nP(1,0)=n−sP(0)s_P(1) = n_P(1, 0) = n - s_P(0). Candidate 0 is in W(P)W(P) exactly when sP(0)≥n−sP(0)s_P(0) \ge n - s_P(0), and then f(P)=0f(P) = 0; otherwise W(P)={1}W(P) = \{1\}. A Condorcet winner has more than n/2n/2 of these pairwise votes, so it is the unique maximizer.

Claim 8 (time). PLURALITY runs in O(n+m)O(n + m) time and O(m)O(m) extra space.

Proof. Line L1 writes mm counters. Each of the nn passes of the loop reads one entry and updates one counter in O(1)O(1) time. Lines L4, L5 and L6 each scan at most mm values. Only the mm counters and the set WW, of size at most mm, are stored. ■\blacksquare

Complexity

Line L1 takes O(m)O(m) time. The loop runs nn times, and each pass reads one entry and does one increment, so it takes O(n)O(n) time when a ballot gives random access to its first entry. Lines L4 to L6 each take O(m)O(m) time. The total is O(n+m)O(n + m) in the word RAM model, with counters of O(log⁡n)O(\log n) bits, and the extra space is the mm counters. If the input is a full profile, it has nmn m entries, but the rule never reads more than nn of them. No algorithm can do better than Ω(n)\Omega(n) when m≥2m \ge 2, since any ballot that it does not read could change the winner.

Properties

These hold for every number of candidates. The proofs are in proofs/correctness.md, and the tests check each one by brute force over all profiles with up to 4 candidates and few voters.

  • Anonymous. Reordering the voters does not change any score.
  • Neutral, as a correspondence. Renaming the candidates renames the scores and the set WW. The resolute rule is not neutral: with one voter a≻ba \succ b and one voter b≻ab \succ a, it elects aa, and after the swap of the names it still elects aa.
  • Pareto. If every voter ranks aa above bb, then no voter ranks bb first, so sP(b)=0s_P(b) = 0, while the winner has at least n/m>0n/m > 0 first places. So bb does not win when n≥1n \ge 1.
  • Monotone. Raising the winner ww on one ballot either leaves all scores the same or moves one first place to ww. Both keep ww in WW and keep it the smallest maximizer, since no other score goes up.
  • Consistent. If two disjoint groups of voters have winner sets W1W_1 and W2W_2 with W1∩W2≠∅W_1 \cap W_2 \neq \emptyset, then the combined group has winner set W1∩W2W_1 \cap W_2, because the scores add. This is the consistency (reinforcement) axiom, and Young (1975) proved that, with anonymity, neutrality and a continuity condition, it characterizes the scoring rules, of which plurality is the simplest.
  • Not Condorcet consistent, and it can elect the Condorcet loser. The example shows both failures.
  • Not strategyproof for 3 or more candidates. The example shows a manipulation by the two voters c≻b≻ac \succ b \succ a. This is forced by the Gibbard-Satterthwaite theorem: plurality is onto and not a dictatorship, so some profile has a profitable false ballot.
  • Majority rule for 2 candidates. With m=2m = 2 the plurality winner is the majority winner, and the rule is then strategyproof and Condorcet consistent. May's theorem characterizes it there.

Variants and improvements

  • Plurality with runoff. If no candidate has more than half of the votes, hold a second round between the top two. The two-round system of French presidential elections works this way. It is still not Condorcet consistent, and it is not monotone.
  • Instant-runoff voting. Ask for full rankings and remove the weakest candidate one at a time. See instant-runoff voting.
  • Approval voting. Let each voter approve any set of candidates. See approval voting.
  • Other scoring rules. Plurality gives 1 point to the top place and 0 to the others. The Borda count gives m−jm - j points to place jj, kk-approval gives 1 point to each of the top kk places, and the veto rule (anti-plurality) gives 1 point to every place except the last. All of them are consistent, and none of them is Condorcet consistent.
  • Multiwinner forms. Single non-transferable vote and block voting elect the kk candidates with the most votes. The single transferable vote is the proportional form.

When to use it

Use plurality when ballots must be as simple as possible, the count must be done by hand or explained in one sentence, and the field has two strong candidates. Then the rule is almost majority rule. With three or more serious candidates, especially when two of them split one group of voters, use a rule that reads more of each ranking: instant-runoff voting if you want a majority in the last round, a Condorcet method such as the Copeland method or ranked pairs if you want the pairwise winner, or approval voting if you want a simple ballot that is safe for sincere voters.

Pitfalls

  • An unstated tie rule. Line L6 is part of the rule. Python's max(range(m), key=s.__getitem__) returns the first maximizer, which is the smallest index here, but max over a dictionary depends on the insertion order. State the rule, and return the set WW of line L5 when the caller must see the ties.
  • Plurality is not majority. In the example the winner has 4 of 9 votes. Code that checks "more than half" to decide the winner implements a different rule, one that can return no winner.
  • Reading the wrong entry. In line L3 the top of the ballot is r[0] in 0-based code. A ballot stored as a position vector (the place of each candidate) and not as a ranking gives wrong counts without any error.
  • Percentages in floating point. Compare the integer counts of line L4, not shares such as s[a]/ns[a]/n, where two equal counts can give shares that differ in the last bit after other arithmetic.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

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))
plurality_voting.py 34 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/plurality-voting/. The authors are listed in prov/WM09B3.jsonl.

from typing import Sequence

Ranking = Sequence[int]


def plurality_scores(profile: Sequence[Ranking], m: int) -> list[int]:
    """Return s with s[a] the number of voters who rank candidate a first.

    The candidates are 0, ..., m - 1 and each ranking lists them best first. Only the first
    entry of each ranking is read, so the time is O(n + m) for n voters.
    """
    s = [0] * m  # @line L1
    for r in profile:  # @line L2
        s[r[0]] += 1  # @line L3
    return s


def plurality_winners(profile: Sequence[Ranking], m: int) -> frozenset[int]:
    """Return the set of candidates with the most first places (the plurality correspondence)."""
    s = plurality_scores(profile, m)
    best = max(s)  # @line L4
    return frozenset(a for a in range(m) if s[a] == best)  # @line L5


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

    Precondition: m >= 1. With no voters every candidate has 0 first places, so candidate 0
    wins. Time O(n + m), extra space O(m).
    """
    return min(plurality_winners(profile, m))  # @line L6
test_plurality_voting.py 273 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/plurality-voting/. The authors are listed in prov/WM09B3.jsonl.

import itertools
import math
import random
from collections import Counter

import agtprefs
from agtprefs import (all_profiles, all_rankings, check_anonymity, check_condorcet_consistency,
                      check_monotonicity, check_neutrality, check_pareto, condorcet_winner,
                      find_manipulation, is_single_peaked_on, kendall_tau, lex_tiebreak, margins,
                      pairwise, permute_profile, position, prefers, random_approval_profile,
                      random_profile, weak_condorcet_winners)
from plurality_voting import plurality, plurality_scores, plurality_winners

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

# The worked example of the page: 4 voters a > b > c, 3 voters b > c > a, 2 voters c > b > a.
EXAMPLE = ((A, B, C),) * 4 + ((B, C, A),) * 3 + ((C, B, A),) * 2
CYCLE = ((A, B, C), (B, C, A), (C, A, B))


# ---------------------------------------------------------------- the shared helper


def test_helper_counts_rankings_and_profiles():
    for m in range(0, 6):
        rs = all_rankings(m)
        assert len(rs) == math.factorial(m)
        assert len(set(rs)) == len(rs)
        assert rs == sorted(rs)
    assert sum(1 for _ in all_profiles(3, 2)) == 36
    assert sum(1 for _ in all_profiles(2, 3)) == 8


def test_helper_condorcet_cycle_check_value():
    M = margins(CYCLE, 3)
    assert M[A][B] == 1 and M[B][C] == 1 and M[C][A] == 1
    assert M[B][A] == -1 and M[C][B] == -1 and M[A][C] == -1
    assert condorcet_winner(CYCLE, 3) is None
    assert weak_condorcet_winners(CYCLE, 3) == frozenset()


def test_helper_pairwise_matches_brute_force():
    rng = random.Random(11)
    for _ in range(300):
        m, n = rng.randint(1, 5), rng.randint(0, 6)
        P = random_profile(rng, m, n)
        N = pairwise(P, m)
        M = margins(P, m)
        for a in range(m):
            assert N[a][a] == 0
            for b in range(m):
                if a != b:
                    assert N[a][b] == sum(1 for r in P if prefers(r, a, b))
                    assert N[a][b] + N[b][a] == n
                    assert M[a][b] == -M[b][a]
        cw = [a for a in range(m) if all(2 * N[a][b] > n for b in range(m) if b != a)]
        assert condorcet_winner(P, m) == (cw[0] if cw else None)
        weak = {a for a in range(m) if all(2 * N[a][b] >= n for b in range(m) if b != a)}
        assert weak_condorcet_winners(P, m) == weak
        if cw:
            assert weak == {cw[0]}


def test_helper_positions_kendall_and_tiebreak():
    rng = random.Random(12)
    for _ in range(300):
        m = rng.randint(1, 6)
        r1 = tuple(rng.sample(range(m), m))
        r2 = tuple(rng.sample(range(m), m))
        for a in range(m):
            assert r1[position(r1, a)] == a
        want = sum(1 for a, b in itertools.combinations(range(m), 2)
                   if prefers(r1, a, b) != prefers(r2, a, b))
        assert kendall_tau(r1, r2) == want == kendall_tau(r2, r1)
        assert kendall_tau(r1, r1) == 0
        assert kendall_tau(r1, tuple(reversed(r1))) == m * (m - 1) // 2
    assert lex_tiebreak({3, 1, 2}) == 1


def _single_peaked_brute(r, axis):
    where = {a: i for i, a in enumerate(axis)}
    peak = where[r[0]]
    for x, y in itertools.permutations(r, 2):
        px, py = where[x], where[y]
        # On one side of the peak, the candidate closer to the peak must be preferred.
        if (py < px <= peak or peak <= px < py) and not prefers(r, x, y):
            return False
    return True


def test_helper_single_peaked_matches_definition():
    for m in range(1, 6):
        for axis in itertools.permutations(range(m)):
            if m == 5 and axis != tuple(range(m)):
                continue
            count = 0
            for r in all_rankings(m):
                ok = is_single_peaked_on((r,), axis)
                assert ok == _single_peaked_brute(r, axis)
                count += ok
            # A known count: 2^(m - 1) rankings are single-peaked on a fixed axis.
            assert count == 2 ** (m - 1)
    assert is_single_peaked_on(((1, 0, 2), (2, 1, 0)), (0, 1, 2))
    assert not is_single_peaked_on(((1, 0, 2), (0, 2, 1)), (0, 1, 2))


def test_helper_random_profiles_and_permutation():
    rng = random.Random(13)
    P = random_profile(rng, 4, 50)
    assert len(P) == 50 and all(sorted(r) == [0, 1, 2, 3] for r in P)
    Q = random_approval_profile(random.Random(14), 5, 400, 0.3)
    assert all(isinstance(b, frozenset) and b <= set(range(5)) for b in Q)
    share = sum(len(b) for b in Q) / (5 * 400)
    assert abs(share - 0.3) < 0.05
    assert random_profile(random.Random(7), 3, 5) == random_profile(random.Random(7), 3, 5)
    pi = (2, 0, 1)
    assert permute_profile(((0, 1, 2),), pi) == ((2, 0, 1),)
    assert permute_profile((frozenset({0, 2}),), pi) == (frozenset({2, 1}),)


def dictator(P, m):
    return P[0][0] if P else 0


def constant(P, m):
    return 0


def test_helper_checkers_on_dictatorship_and_constant_rule():
    for m, n in [(3, 2), (3, 3), (2, 3)]:
        # A dictatorship is neutral, Pareto, monotone and strategyproof, but not anonymous.
        assert check_anonymity(dictator, m, n) is not None
        assert check_neutrality(dictator, m, n) is None
        assert check_pareto(dictator, m, n) is None
        assert check_monotonicity(dictator, m, n) is None
        assert find_manipulation(dictator, m, n) is None
        # A constant rule is anonymous, monotone and strategyproof, but not neutral or Pareto.
        assert check_anonymity(constant, m, n) is None
        assert check_neutrality(constant, m, n) is not None
        assert check_pareto(constant, m, n) is not None
        assert check_monotonicity(constant, m, n) is None
        assert find_manipulation(constant, m, n) is None
    # With 3 voters, voter 0 can be outvoted by a majority that prefers b to the dictator's a.
    P, c = check_condorcet_consistency(dictator, 3, 3)
    assert condorcet_winner(P, 3) == c != P[0][0]


def test_helper_counterexamples_are_real():
    P, Q = check_anonymity(dictator, 3, 2)
    assert sorted(P) == sorted(Q) and dictator(P, 3) != dictator(Q, 3)
    P, pi = check_neutrality(constant, 3, 2)
    assert constant(permute_profile(P, pi), 3) != pi[constant(P, 3)]
    P, a, b = check_pareto(constant, 3, 2)
    assert b == 0 and all(prefers(r, a, b) for r in P)

    def anti_plurality_top(P, m):  # elects the candidate with the fewest first places
        s = plurality_scores(P, m)
        return min(range(m), key=lambda a: (s[a], a))

    P, Q, w = check_monotonicity(anti_plurality_top, 3, 2)
    assert anti_plurality_top(P, 3) == w != anti_plurality_top(Q, 3)
    P, i, s = find_manipulation(anti_plurality_top, 3, 2)
    Q = P[:i] + (s,) + P[i + 1:]
    assert prefers(P[i], anti_plurality_top(Q, 3), anti_plurality_top(P, 3))


# ---------------------------------------------------------------- plurality voting


def test_worked_example():
    assert plurality_scores(EXAMPLE, 3) == [4, 3, 2]
    assert plurality(EXAMPLE, 3) == A
    # b is the Condorcet winner, and the plurality winner a is the Condorcet loser.
    assert condorcet_winner(EXAMPLE, 3) == B
    M = margins(EXAMPLE, 3)
    assert M[A][B] == -1 and M[A][C] == -1 and M[B][C] == 5
    # The two voters c > b > a gain by voting b > c > a.
    lie = ((A, B, C),) * 4 + ((B, C, A),) * 5
    assert plurality(lie, 3) == B


def test_matches_counter_on_random_profiles():
    rng = random.Random(21)
    for _ in range(2000):
        m, n = rng.randint(1, 6), rng.randint(0, 12)
        P = random_profile(rng, m, n)
        tops = Counter(r[0] for r in P)
        s = plurality_scores(P, m)
        assert s == [tops[a] for a in range(m)]
        assert sum(s) == n
        best = max(s)
        W = {a for a in range(m) if tops[a] == best}
        assert plurality_winners(P, m) == W
        assert plurality(P, m) == min(W)


def test_edge_cases():
    assert plurality((), 3) == 0 and plurality_winners((), 3) == {0, 1, 2}
    assert plurality(((0,),), 1) == 0
    assert plurality(((2, 1, 0), (1, 2, 0)), 3) == 1  # a tie of 1 and 2 goes to 1
    assert plurality_winners(CYCLE, 3) == {A, B, C} and plurality(CYCLE, 3) == A


def test_axioms_by_brute_force():
    for m, n in [(3, 3), (3, 4), (4, 2)]:
        assert check_anonymity(plurality, m, n) is None
        assert check_anonymity(plurality_winners, m, n) is None
        assert check_neutrality(plurality_winners, m, n) is None
        assert check_pareto(plurality, m, n) is None
        assert check_monotonicity(plurality, m, n) is None
        assert check_monotonicity(plurality_winners, m, n) is None
    # The resolute rule with the fixed tie-break is not neutral.
    P, pi = check_neutrality(plurality, 3, 2)
    assert plurality(permute_profile(P, pi), 3) != pi[plurality(P, 3)]


def test_failures_by_search():
    # Not Condorcet consistent, and open to manipulation, for 3 candidates.
    P, c = check_condorcet_consistency(plurality, 3, 3)
    assert plurality(P, 3) != c
    P, i, s = find_manipulation(plurality, 3, 3)
    Q = P[:i] + (s,) + P[i + 1:]
    assert prefers(P[i], plurality(Q, 3), plurality(P, 3))
    # With 3 candidates, a Condorcet loser can win alone (no tie) only with 7 or more voters.
    def condorcet_loser(P, m):
        M = margins(P, m)
        losers = [a for a in range(m) if all(M[a][b] < 0 for b in range(m) if b != a)]
        return losers[0] if losers else None

    def loser_wins_alone(P):
        W = plurality_winners(P, 3)
        return len(W) == 1 and condorcet_loser(P, 3) in W

    for n in range(1, 7):
        assert not any(loser_wins_alone(P) for P in all_profiles(3, n))
    smallest = ((A, B, C),) * 3 + ((B, C, A),) * 2 + ((C, B, A),) * 2
    assert loser_wins_alone(smallest)
    # With the tie-break, 3 voters suffice: a, b and c each have one first place, and a wins.
    tied = ((A, B, C), (B, C, A), (C, B, A))
    assert plurality(tied, 3) == A == condorcet_loser(tied, 3)


def test_consistency_by_brute_force():
    # If two groups of voters have overlapping winner sets, the joined group elects the overlap.
    for n1, n2 in [(1, 1), (1, 2), (2, 2)]:
        groups1 = list(all_profiles(3, n1))
        groups2 = list(all_profiles(3, n2))
        checked = 0
        for P1 in groups1:
            W1 = plurality_winners(P1, 3)
            for P2 in groups2:
                both = W1 & plurality_winners(P2, 3)
                if both:
                    assert plurality_winners(P1 + P2, 3) == both
                    checked += 1
        assert checked > 0


def test_two_candidates_is_majority_rule():
    for n in range(1, 8):
        for P in all_profiles(2, n):
            k = sum(1 for r in P if r[0] == 0)
            assert plurality(P, 2) == (0 if 2 * k >= n else 1)
        assert find_manipulation(plurality, 2, n) is None
        assert check_condorcet_consistency(plurality, 2, n) is None


def test_helper_module_has_no_rule():
    names = {x for x in dir(agtprefs) if not x.startswith("_")}
    assert not any("plurality" in x or "borda" in x for x in names)

History

Plurality is the oldest and most common rule for elections. Borda, in a memoir printed in 1784, argued that it can elect a candidate whom a majority ranks last, and proposed his scoring rule in its place. Condorcet answered with the pairwise majority test. Gibbard (1973) and Satterthwaite (1975) proved that every onto rule with three or more possible winners that is not a dictatorship can be manipulated, so the strategic voting that plurality invites is not a defect of this rule alone. Young (1975) placed plurality in the family of scoring rules by the consistency axiom.

References

  1. Felix Brandt, Vincent Conitzer, Ulle Endriss, Jérôme Lang and Ariel D. Procaccia (eds.), Handbook of Computational Social Choice, Cambridge University Press, 2016, Chapter 2 (William S. Zwicker, Introduction to the theory of voting), Section 2.2 (plurality, Copeland and Borda) and Section 2.4 (scoring rules and runoffs)
  2. H. P. Young, Social choice scoring functions, SIAM Journal on Applied Mathematics 28(4) (1975), 824-838, the characterization of the scoring rules, of which plurality is one, by consistency with anonymity, neutrality and a continuity condition
  3. Jean-Charles de Borda, Mémoire sur les élections au scrutin, Histoire de l'Académie Royale des Sciences, année 1781 (printed 1784), 657-665, the argument that plurality can elect a candidate whom a majority ranks last
  4. Allan Gibbard, Manipulation of voting schemes, a general result, Econometrica 41(4) (1973), 587-601, the main theorem, which applies to plurality with three or more candidates

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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