Algorithm Search⌘K

Algorithmcore

Power indices by dynamic programming

Also called generating function method for voting power.

Computes the Banzhaf and Shapley-Shubik indices of a weighted voting game in time pseudo-polynomial in the weights by counting coalitions.

Time
O(n^3 q) worstO(n^2 q) banzhaf
Space
O(n q) extra
Where
n = the number of players; q = the quota
Properties
deterministicexactofflineiterative
Origin
Irwin Mann, Lloyd S. Shapley, Tomomi Matsui, Yasuko Matsui, 1962

This algorithm computes the Banzhaf and Shapley-Shubik indices of a weighted voting game [q;w1,…,wn][q; w_1, \ldots, w_n] with integer weights exactly. Both indices only need, for each player ii and each size ss, the number of coalitions of the other players with size ss whose weight lies in the window [q−wi,q−1][q - w_i, q - 1]. A table indexed by size and weight, filled like the table of the 0/1 knapsack dynamic program, gives these counts. The running time is O(n2q)O(n^2 q) arithmetic operations per player, polynomial in nn and in the value of the quota but not in its number of digits, so the algorithm is pseudo-polynomial. That is the best one can expect: with weights in binary, both indices are #P-complete (hardness of power indices).

In plain words

A player has power in a coalition when the coalition is just short of the quota, and the player's weight pushes it over. So we need to know how many groups of the other players have a total weight just below the quota. We build a table that says, for each group size and each total weight, how many groups of the other players have that size and weight. We add the players one by one, as in the knapsack table. Then we read off the groups whose weight is short of the quota by less than the player's weight. Their number gives the Banzhaf index, and their numbers by size give the Shapley-Shubik index.

The problem

The input is a weighted voting game: integer weights w1,…,wn≥0w_1, \ldots, w_n \ge 0 and an integer quota qq with 1≤q≤w(N)1 \le q \le w(N), where w(S)=∑j∈Swjw(S) = \sum_{j \in S} w_j. A coalition SS wins if w(S)≥qw(S) \ge q. A set S⊆N∖{i}S \subseteq N \setminus \{i\} is a swing of player ii if w(S)<q≤w(S)+wiw(S) < q \le w(S) + w_i. The output, for each player ii, is:

  • the number ηi\eta_i of swings of ii;
  • the raw Banzhaf index βi′=ηi/2n−1\beta'_i = \eta_i / 2^{n-1}, and the normalized index ηi/∑jηj\eta_i / \sum_j \eta_j;
  • the Shapley-Shubik index φi=∑S a swing of i∣S∣! (n−∣S∣−1)!/n!\varphi_i = \sum_{S \text{ a swing of } i} |S|!\,(n - |S| - 1)!/n!.

The algorithm

For a player ii, the table C[s][k]C[s][k] counts the sets S⊆N∖{i}S \subseteq N \setminus \{i\} with ∣S∣=s|S| = s and w(S)=kw(S) = k, for 0≤k≤q−10 \le k \le q - 1. Sets of weight qq or more are never needed, so the table stops at q−1q - 1.

  1. POWER-INDICES(w, q, i) ▷ the indices of player i in [q; w_1, ..., w_n]
  2. 1C[s][k] ← 0 for 0 ≤ s ≤ n-1 and 0 ≤ k ≤ q-1; C[0][0] ← 1
  3. 2for each player j ≠ i do
  4. 3for s ← n-2 downto 0 do ▷ downward, so row s is still the old row
  5. 4for k ← q-1-w_j downto 0 do
  6. 5C[s+1][k+w_j] ← C[s+1][k+w_j] + C[s][k]
  7. 6c_s ← the sum of C[s][k] for max(0, q-w_i) ≤ k ≤ q-1, for each 0 ≤ s ≤ n-1
  8. 7β'_i ← (c_0 + c_1 + ... + c_{n-1}) / 2^(n-1)
  9. 8φ_i ← the sum over 0 ≤ s ≤ n-1 of s! (n-1-s)! / n! · c_s
  10. 9return (c_0 + ... + c_{n-1}, β'_i, φ_i)

Run it once for each player, and divide the swing counts by their total for the normalized Banzhaf index. If wj≥qw_j \ge q, the loop of line L4 is empty: every set that contains jj has weight at least qq and is never counted.

Example

Take [51;50,49,1][51; 50, 49, 1] and player 1, with w1=50w_1 = 50. The other weights are 49 and 1. The table starts with C[0][0]=1C[0][0] = 1.

  • Add player 2 (w2=49w_2 = 49). For s=1s = 1 nothing is stored yet. For s=0s = 0, line L5 sets C[1][49]=1C[1][49] = 1.
  • Add player 3 (w3=1w_3 = 1). For s=1s = 1, line L5 adds C[1][49]C[1][49] to C[2][50]C[2][50], so C[2][50]=1C[2][50] = 1. For s=0s = 0, it adds C[0][0]C[0][0] to C[1][1]C[1][1], so C[1][1]=1C[1][1] = 1.

The nonzero entries are C[0][0]=1C[0][0] = 1 (the empty set), C[1][1]=1C[1][1] = 1 ({3}\{3\}), C[1][49]=1C[1][49] = 1 ({2}\{2\}) and C[2][50]=1C[2][50] = 1 ({2,3}\{2, 3\}). The window is max⁡(0,51−50)=1≤k≤50\max(0, 51 - 50) = 1 \le k \le 50, so c0=0c_0 = 0, c1=2c_1 = 2 and c2=1c_2 = 1. Player 1 has 3 swings, and

β1′=34,φ1=1! 1!3!⋅2+2! 0!3!⋅1=13+13=23.\beta'_1 = \frac{3}{4}, \qquad \varphi_1 = \frac{1!\,1!}{3!} \cdot 2 + \frac{2!\,0!}{3!} \cdot 1 = \frac{1}{3} + \frac{1}{3} = \frac{2}{3}.

For player 2 (w2=49w_2 = 49), the other weights are 50 and 1. The set {1,3}\{1, 3\} has weight 51 and is never stored. The window is 2≤k≤502 \le k \le 50, which holds only {1}\{1\} with weight 50, so c1=1c_1 = 1, β2′=1/4\beta'_2 = 1/4 and φ2=1/6\varphi_2 = 1/6. Player 3 is the same by symmetry of the game. The swings are 3,1,13, 1, 1, the normalized Banzhaf index is (3/5,1/5,1/5)(3/5, 1/5, 1/5) and the Shapley-Shubik index is (2/3,1/6,1/6)(2/3, 1/6, 1/6).

For the Council of the EEC in 1958, [12;4,4,4,2,2,1][12; 4, 4, 4, 2, 2, 1], the same steps give the swing counts (10,10,10,6,6,0)(10, 10, 10, 6, 6, 0) and the Shapley-Shubik index (7/30,7/30,7/30,3/20,3/20,0)(7/30, 7/30, 7/30, 3/20, 3/20, 0).

Correctness

The invariant of the loop of line L2 is that C[s][k]C[s][k] counts the subsets of the players handled so far with size ss and weight kk, for every k≤q−1k \le q - 1. Adding player jj splits each new set into the sets without jj (the old entry) and the sets with jj (the old entry at size s−1s - 1 and weight k−wjk - w_j). The downward loop of line L3 makes every read of row ss see the old value, because row ss is written only later, at the step s−1s - 1. Dropping the sets of weight qq or more is safe, because adding players never lowers a weight. At the end, the window of line L6 is exactly the set of weights of the swings of ii. The Shapley-Shubik index is the Shapley value of the game, and its subset formula groups the swings by size, which gives line L8. The full proofs are in the proof file.

Proof: The table counts the swings of each size, and the indices follow from these countsfull

The game is [q;w1,…,wn][q; w_1, \ldots, w_n] with nonnegative integer weights and an integer quota 1≤q≤w(N)1 \le q \le w(N). A coalition SS wins if w(S)≥qw(S) \ge q. Fix the player ii and let JJ be the set of the players j≠ij \ne i that the loop of line L2 has handled so far.

Lemma (table). After the loop of line L2 has handled the players in JJ, for each 0≤s≤n−10 \le s \le n-1 and 0≤k≤q−10 \le k \le q-1, the entry C[s][k]C[s][k] is the number of sets S⊆JS \subseteq J with ∣S∣=s|S| = s and w(S)=kw(S) = k.

Proof. By induction on ∣J∣|J|. Line L1 sets C[0][0]=1C[0][0] = 1 and every other entry to 0. For J=∅J = \emptyset the only subset is ∅\emptyset, with size 0 and weight 0, so the claim is true.

Assume that the claim is true for JJ and that line L2 now handles the player jj. Write CC for the table before this step and C′C' for the table after it. A set S′⊆J∪{j}S' \subseteq J \cup \{j\} with ∣S′∣=s+1|S'| = s + 1 and w(S′)=k′w(S') = k' either does not contain jj, and then it is a subset of JJ of the same size and weight, or it contains jj, and then S′∖{j}S' \setminus \{j\} is a subset of JJ with size ss and weight k′−wjk' - w_j. So the correct new value is C′[s+1][k′]=C[s+1][k′]+C[s][k′−wj]C'[s+1][k'] = C[s+1][k'] + C[s][k' - w_j], where the second term is 0 if k′<wjk' < w_j. The entries of row 0 do not change, which is correct, because the only set of size 0 is ∅\emptyset.

We show that lines L3 to L5 compute exactly this. Line L5 at the step (s,k)(s, k) reads C[s][k]C[s][k] and adds it to C[s+1][k+wj]C[s+1][k+w_j]. The loop of line L3 goes down from s=n−2s = n-2 to s=0s = 0. At the step ss, row s+1s+1 is written. Row s+1s+1 was read only at the earlier step s+1s+1, and row ss is written only at the later step s−1s-1. So every read of row ss sees the value from before the handling of jj, even when wj=0w_j = 0, because the read and the write are always in different rows. Inside one step ss the reads are in row ss and the writes in row s+1s+1, so the order of kk does not matter.

Line L4 takes each kk with 0≤k0 \le k and k+wj≤q−1k + w_j \le q-1, so line L5 adds C[s][k′−wj]C[s][k'-w_j] to each entry C[s+1][k′]C[s+1][k'] with wj≤k′≤q−1w_j \le k' \le q-1, and to no other entry. For k′<wjk' < w_j the correct second term is 0, and the entry does not change. So $C' = $ the correct table on the range 0≤k′≤q−10 \le k' \le q-1. The loop of line L3 covers the rows s+1s + 1 from 11 to n−1n-1, and a subset of JJ has at most n−1n-1 players, so no size is missed.

One more point needs care: line L5 drops each set of weight qq or more. This is safe, because a set of weight at least qq only grows in weight when the later steps add players to it, since the weights are nonnegative. So no entry with k≤q−1k \le q-1 ever needs a count of a set of weight qq or more. □\square

Lemma (swings). After the loop of line L2 ends, line L6 sets csc_s to the number of swings of ii of size ss: sets S⊆N∖{i}S \subseteq N \setminus \{i\} with ∣S∣=s|S| = s, w(S)≤q−1w(S) \le q-1 and w(S)+wi≥qw(S) + w_i \ge q.

Proof. At the end, J=N∖{i}J = N \setminus \{i\}. A set S⊆JS \subseteq J is a swing if and only if q−wi≤w(S)≤q−1q - w_i \le w(S) \le q-1, which is max⁡(0,q−wi)≤w(S)≤q−1\max(0, q - w_i) \le w(S) \le q-1 since weights are nonnegative. Line L6 adds the entries C[s][k]C[s][k] for exactly these kk, and by the table lemma each entry counts the sets of size ss and weight kk. □\square

Theorem. Line L7 returns the raw Banzhaf index βi\beta_i of ii, and line L8 returns the Shapley-Shubik index φi\varphi_i of ii.

Proof. The game is monotone: if S⊆TS \subseteq T then w(S)≤w(T)w(S) \le w(T), so v(S)≤v(T)v(S) \le v(T). Hence the marginal contribution v(S∪{i})−v(S)v(S \cup \{i\}) - v(S) of ii to a set S∌iS \not\ni i is 0 or 1, and it is 1 exactly when SS is a swing of ii.

The raw Banzhaf index is the mean of the marginal contribution over the 2n−12^{n-1} sets S⊆N∖{i}S \subseteq N \setminus \{i\}, so it is the number of swings divided by 2n−12^{n-1}. By the swings lemma, this number is ∑scs\sum_s c_s, which line L7 uses.

The Shapley-Shubik index is the Shapley value of the simple game. By the subset formula,

φi=∑S⊆N∖{i}∣S∣! (n−∣S∣−1)!n!(v(S∪{i})−v(S)).\varphi_i = \sum_{S \subseteq N \setminus \{i\}} \frac{|S|!\,(n-|S|-1)!}{n!} \big(v(S \cup \{i\}) - v(S)\big).

The weight depends only on ∣S∣|S|, and the bracket is 1 for the swings and 0 for the other sets. If we group the sets by size, the sum is ∑s=0n−1s! (n−1−s)!n!cs\sum_{s=0}^{n-1} \frac{s!\,(n-1-s)!}{n!} c_s, which is line L8. ■\blacksquare

Normalized index. The normalized Banzhaf index divides the swings of ii by the sum of the swings of all players. This sum is positive: in each order of the players, the first player whose arrival takes the weight to qq or more is a swing for the set of the players before it, and such a player exists because w(N)≥qw(N) \ge q and w(∅)=0<qw(\emptyset) = 0 < q.

Complexity

  • Time per player. Lines L2 to L5 run n−1n - 1 times over n−1n - 1 rows and at most qq columns, so O(n2q)O(n^2 q) additions. Lines L6 to L8 add O(nq)O(n q) more. All nn players take O(n3q)O(n^3 q).
  • Banzhaf only. Without the size index, the table is one row of length qq, filled as in the subset sum counting program, in O(nq)O(n q) per player and O(n2q)O(n^2 q) for all players.
  • Space. O(nq)O(n q) numbers for the table, or O(q)O(q) for the Banzhaf index alone.
  • Number size. The counts reach (n−1s)<2n−1\binom{n-1}{s} < 2^{n-1}, so they have up to nn bits. On a word RAM with ww-bit words, each addition costs O(⌈n/w⌉)O(\lceil n / w \rceil) word operations, which adds this factor to the bounds above. The final fractions have denominators 2n−12^{n-1} and n!n!.

The bounds are pseudo-polynomial: they depend on the value qq, which can be exponential in the input length. Since q≤w(N)≤n wmax⁡q \le w(N) \le n\, w_{\max}, they are polynomial when the weights are bounded by a polynomial in nn, for example when the weights are seat counts or votes written in unary. The hardness theorem shows that the dependence on qq cannot be removed unless P = NP, so the problem is only weakly NP-hard.

Properties

  • Exact. The counts are integers and the indices are exact rationals. No rounding is involved.
  • Deterministic.
  • Per player. One run gives the indices of one player, but the variant below gives all players from one table.
  • Truncated at the quota. Only the weights below qq are stored, which also bounds the table by qq and not by w(N)w(N).

Variants and improvements

  • Deletion instead of recomputation. Build the table once with all nn players, in O(n2q)O(n^2 q) time. The table without player ii follows from it by running line L5 backwards: for ss upward from 1, C−i[s][k]=C[s][k]−C−i[s−1][k−wi]C_{-i}[s][k] = C[s][k] - C_{-i}[s-1][k - w_i]. This takes O(nq)O(n q) per player, so all Shapley-Shubik indices take O(n2q)O(n^2 q) in total, and all Banzhaf indices O(nq)O(n q). The truncation at qq stays valid, because a set of weight k<qk < q with ii comes from a set of weight k−wi<qk - w_i < q without ii.
  • Generating functions. The counts are the coefficients of ∏j≠i(1+y xwj)\prod_{j \ne i} (1 + y\, x^{w_j}), where xx marks the weight and yy the size. Multiplying the factors one by one is the table above. With fast polynomial multiplication, a product tree speeds up the computation when qq is large compared with nn.
  • Other indices. The same table gives every index that depends only on the number of swings of each size, such as the semivalues.
  • Large weights. When qq is too large for a table, use sampling for an additive approximation, or a table keyed by the weights that occur, which is small when many players share the same weight.

When to use it

Use it for exact indices of a voting body whose weights are moderate integers: seat counts of parties, votes in a council, or weights scaled to integers. A council of 30 members with weights up to a few thousand is computed in a fraction of a second. For weights in the millions, such as shares or populations, the table grows with qq, and sampling or a coarser exact weighting may be better. For other compact games, use the representation that fits, for example marginal contribution nets.

Pitfalls

  • The direction of the loop. Line L3 must go down in ss, or line L4 must go down in kk when there is no size index. An upward loop counts sets that contain player jj twice, which is the unbounded knapsack and gives wrong counts.
  • The window. The lower end is max⁡(0,q−wi)\max(0, q - w_i), not q−wiq - w_i, and the upper end is q−1q - 1. A player with wi≥qw_i \ge q swings for every losing coalition of the others.
  • The quota convention. "More than half of WW" means q=⌊W/2⌋+1q = \lfloor W/2 \rfloor + 1. "At least half" is a different game when WW is even, with different indices.
  • Rounding weights. Scaling real weights to integers and rounding can change the game, because a coalition near the quota can flip from losing to winning. Scale exactly, or check that no coalition weight lies near the quota.
  • Overflow. The counts reach 2n−12^{n-1}, which overflows 64-bit integers for n>64n > 64. Use big integers or exact fractions.
  • Raw against normalized. The raw Banzhaf indices do not sum to 1. Say which form a table uses.

Implementations

The Python version returns the swing counts, both Banzhaf forms and the Shapley-Shubik index as exact Fractions, and rejects negative weights and a quota outside [1,w(N)][1, w(N)].

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.

power_index_dynamic_programming.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/power-index-dynamic-programming/. The authors are listed in prov/MQFKCA.jsonl.
"""Banzhaf and Shapley-Shubik indices of a weighted voting game by dynamic programming.

The game [q; w_1, ..., w_n] has nonnegative integer weights and an integer quota q with
1 <= q <= sum(w). A coalition S wins if w(S) >= q. Players are 0 to n - 1. The counts are
exact integers and the indices are Fractions.
"""

from fractions import Fraction
from math import factorial


def check_game(weights: list[int], q: int) -> None:
    """Raise ValueError unless the weights are nonnegative integers and 1 <= q <= sum(weights)."""
    if any(not isinstance(x, int) or x < 0 for x in weights):
        raise ValueError("weights must be nonnegative integers")
    if not isinstance(q, int) or q < 1 or q > sum(weights):
        raise ValueError("the quota must satisfy 1 <= q <= sum of the weights")


def swings_by_size(weights: list[int], q: int, i: int) -> list[int]:
    """c[s] = the number of coalitions S of the other players with |S| = s and q - w_i <= w(S) <= q - 1.

    These are the coalitions that player i turns from losing into winning (the swings of i).
    """
    n = len(weights)
    table = [[0] * q for _ in range(n)]  # @line L1: table[s][k] counts sets of size s and weight k < q
    table[0][0] = 1
    for j in range(n):  # @line L2
        if j == i:
            continue
        wj = weights[j]
        for s in range(n - 2, -1, -1):  # @line L3: downward, so row s is still the old row
            row, up = table[s], table[s + 1]
            for k in range(q - 1 - wj, -1, -1):  # @line L4: a set of weight >= q is never counted
                if row[k]:
                    up[k + wj] += row[k]  # @line L5
    lo = max(0, q - weights[i])
    return [sum(table[s][lo:q]) for s in range(n)]  # @line L6


def player_indices(weights: list[int], q: int, i: int) -> tuple[int, Fraction, Fraction]:
    """Return (swings of i, raw Banzhaf index of i, Shapley-Shubik index of i)."""
    check_game(weights, q)
    n = len(weights)
    c = swings_by_size(weights, q, i)
    swings = sum(c)
    beta = Fraction(swings, 2 ** (n - 1))  # @line L7
    nf = factorial(n)
    phi = sum((Fraction(factorial(s) * factorial(n - 1 - s), nf) * c[s] for s in range(n)), Fraction(0))  # @line L8
    return swings, beta, phi  # @line L9


def power_indices(weights: list[int], q: int) -> dict[str, list]:
    """All indices of all players: swings, raw Banzhaf, normalized Banzhaf and Shapley-Shubik."""
    check_game(weights, q)
    rows = [player_indices(weights, q, i) for i in range(len(weights))]
    swings = [r[0] for r in rows]
    total = sum(swings)  # positive, because some player is pivotal in every order
    return {
        "swings": swings,
        "banzhaf_raw": [r[1] for r in rows],
        "banzhaf_normalized": [Fraction(x, total) for x in swings],
        "shapley_shubik": [r[2] for r in rows],
    }
test_power_index_dynamic_programming.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/power-index-dynamic-programming/. The authors are listed in prov/MQFKCA.jsonl.

import random
from fractions import Fraction
from itertools import combinations, permutations
from math import comb, factorial

import pytest

from power_index_dynamic_programming import player_indices, power_indices, swings_by_size


def wins(weights, q, S):
    return sum(weights[j] for j in S) >= q


def brute_swings(weights, q, i):
    others = [j for j in range(len(weights)) if j != i]
    return sum(
        1
        for r in range(len(others) + 1)
        for S in combinations(others, r)
        if not wins(weights, q, S) and wins(weights, q, S + (i,))
    )


def brute_shapley_shubik(weights, q, i):
    """The subset formula of the Shapley value for the simple game."""
    n = len(weights)
    others = [j for j in range(n) if j != i]
    total = Fraction(0)
    for r in range(n):
        for S in combinations(others, r):
            if not wins(weights, q, S) and wins(weights, q, S + (i,)):
                total += Fraction(factorial(r) * factorial(n - 1 - r), factorial(n))
    return total


def pivot_counts(weights, q):
    """Count, over all n! orders, how often each player is the pivot."""
    n = len(weights)
    count = [0] * n
    for order in permutations(range(n)):
        t = 0
        for j in order:
            t += weights[j]
            if t >= q:
                count[j] += 1
                break
    return count


def test_check_value_51_50_49_1():
    r = power_indices([50, 49, 1], 51)
    assert r["swings"] == [3, 1, 1]
    assert r["banzhaf_raw"] == [Fraction(3, 4), Fraction(1, 4), Fraction(1, 4)]
    assert r["banzhaf_normalized"] == [Fraction(3, 5), Fraction(1, 5), Fraction(1, 5)]
    assert r["shapley_shubik"] == [Fraction(2, 3), Fraction(1, 6), Fraction(1, 6)]


def test_eec_1958_council():
    r = power_indices([4, 4, 4, 2, 2, 1], 12)
    assert r["swings"] == [10, 10, 10, 6, 6, 0]
    assert r["banzhaf_normalized"] == [Fraction(5, 21)] * 3 + [Fraction(1, 7)] * 2 + [Fraction(0)]
    assert r["shapley_shubik"] == [Fraction(7, 30)] * 3 + [Fraction(3, 20)] * 2 + [Fraction(0)]


def test_swings_by_size_small():
    # [51; 50, 49, 1], player 0: the swings are {1} and {2} (size 1) and {1, 2} (size 2).
    assert swings_by_size([50, 49, 1], 51, 0) == [0, 2, 1]


def test_random_against_enumeration():
    rng = random.Random(20251120)
    for _ in range(60):
        n = rng.randint(1, 9)
        weights = [rng.randint(0, 12) for _ in range(n)]
        if sum(weights) == 0:
            weights[0] = 1
        q = rng.randint(1, sum(weights))
        r = power_indices(weights, q)
        for i in range(n):
            assert r["swings"][i] == brute_swings(weights, q, i)
            assert r["banzhaf_raw"][i] == Fraction(brute_swings(weights, q, i), 2 ** (n - 1))
            assert r["shapley_shubik"][i] == brute_shapley_shubik(weights, q, i)
        assert sum(r["shapley_shubik"]) == 1
        assert sum(r["banzhaf_normalized"]) == 1


def test_against_orders():
    rng = random.Random(7)
    for _ in range(15):
        n = rng.randint(2, 6)
        weights = [rng.randint(1, 9) for _ in range(n)]
        q = rng.randint(1, sum(weights))
        counts = pivot_counts(weights, q)
        r = power_indices(weights, q)
        assert r["shapley_shubik"] == [Fraction(c, factorial(n)) for c in counts]


def test_equal_weights_closed_form():
    n, k = 14, 8
    r = power_indices([1] * n, k)
    assert r["shapley_shubik"] == [Fraction(1, n)] * n
    assert r["swings"] == [comb(n - 1, k - 1)] * n


def test_large_weights_one_player_dominates():
    # A player with weight at least q swings in every coalition of weight < q.
    weights = [100, 3, 3, 3]
    swings, beta, phi = player_indices(weights, 100, 0)
    assert swings == 8 and beta == 1 and phi == 1


def test_zero_weight_player_is_dummy():
    r = power_indices([3, 0, 2, 2], 4)
    assert r["swings"][1] == 0 and r["shapley_shubik"][1] == 0


def test_bad_input():
    with pytest.raises(ValueError):
        power_indices([1, 2], 0)
    with pytest.raises(ValueError):
        power_indices([1, 2], 4)
    with pytest.raises(ValueError):
        power_indices([1, -2, 5], 3)

History

Mann and Shapley (1962) computed the Shapley-Shubik index of the United States Electoral College exactly at RAND, after an earlier Monte Carlo estimate (1960). Counting the coalitions by weight with generating functions or tables became the standard exact method for weighted voting games. Prasad and Kelly (1990) and Deng and Papadimitriou (1994) proved that the indices are #P-complete, which explains why all exact methods depend on the size of the weights. Matsui and Matsui (2000) surveyed the algorithms for both indices and their running times.

References

  1. Tomomi Matsui and Yasuko Matsui, A survey of algorithms for calculating power indices of weighted majority games, Journal of the Operations Research Society of Japan 43(1) (2000), 71-86, the dynamic programming algorithms for the Banzhaf and Shapley-Shubik indices and their running times in terms of the number of players and the weights
  2. Georgios Chalkiadakis, Edith Elkind and Michael Wooldridge, Computational Aspects of Cooperative Game Theory, Morgan and Claypool, 2011, Chapter 4, Weighted voting games (the pseudo-polynomial algorithm for the power indices and the hardness for large weights)
  3. Kislaya Prasad and Jerry S. Kelly, NP-completeness of some problems concerning voting games, International Journal of Game Theory 19(1) (1990), 1-9, the hardness results that make a pseudo-polynomial algorithm the best one can expect
  4. Xiaotie Deng and Christos H. Papadimitriou, On the complexity of cooperative solution concepts, Mathematics of Operations Research 19(2) (1994), 257-266, the

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.banzhaf
  • 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