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
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 with integer weights exactly. Both indices only need, for each player and each size , the number of coalitions of the other players with size whose weight lies in the window . 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 arithmetic operations per player, polynomial in 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 and an integer quota with , where . A coalition wins if . A set is a swing of player if . The output, for each player , is:
- the number of swings of ;
- the raw Banzhaf index , and the normalized index ;
- the Shapley-Shubik index .
The algorithm
For a player , the table counts the sets with and , for . Sets of weight or more are never needed, so the table stops at .
POWER-INDICES(w, q, i) ▷ the indices of player i in [q; w_1, ..., w_n]- 1
C[s][k] ← 0 for 0 ≤ s ≤ n-1 and 0 ≤ k ≤ q-1; C[0][0] ← 1 - 2
for each player j ≠ i do - 3
for s ← n-2 downto 0 do ▷ downward, so row s is still the old row - 4
for k ← q-1-w_j downto 0 do - 5
C[s+1][k+w_j] ← C[s+1][k+w_j] + C[s][k] - 6
c_s ← the sum of C[s][k] for max(0, q-w_i) ≤ k ≤ q-1, for each 0 ≤ s ≤ n-1 - 7
β'_i ← (c_0 + c_1 + ... + c_{n-1}) / 2^(n-1) - 8
φ_i ← the sum over 0 ≤ s ≤ n-1 of s! (n-1-s)! / n! · c_s - 9
return (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 , the loop of line L4 is empty: every set that contains has weight at least and is never counted.
Example
Take and player 1, with . The other weights are 49 and 1. The table starts with .
- Add player 2 (). For nothing is stored yet. For , line L5 sets .
- Add player 3 (). For , line L5 adds to , so . For , it adds to , so .
The nonzero entries are (the empty set), (), () and (). The window is , so , and . Player 1 has 3 swings, and
For player 2 (), the other weights are 50 and 1. The set has weight 51 and is never stored. The window is , which holds only with weight 50, so , and . Player 3 is the same by symmetry of the game. The swings are , the normalized Banzhaf index is and the Shapley-Shubik index is .
For the Council of the EEC in 1958, , the same steps give the swing counts and the Shapley-Shubik index .
Correctness
The invariant of the loop of line L2 is that counts the subsets of the players handled so far with size and weight , for every . Adding player splits each new set into the sets without (the old entry) and the sets with (the old entry at size and weight ). The downward loop of line L3 makes every read of row see the old value, because row is written only later, at the step . Dropping the sets of weight 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 . 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 with nonnegative integer weights and an integer quota . A coalition wins if . Fix the player and let be the set of the players that the loop of line L2 has handled so far.
Lemma (table). After the loop of line L2 has handled the players in , for each and , the entry is the number of sets with and .
Proof. By induction on . Line L1 sets and every other entry to 0. For the only subset is , with size 0 and weight 0, so the claim is true.
Assume that the claim is true for and that line L2 now handles the player . Write for the table before this step and for the table after it. A set with and either does not contain , and then it is a subset of of the same size and weight, or it contains , and then is a subset of with size and weight . So the correct new value is , where the second term is 0 if . The entries of row 0 do not change, which is correct, because the only set of size 0 is .
We show that lines L3 to L5 compute exactly this. Line L5 at the step reads and adds it to . The loop of line L3 goes down from to . At the step , row is written. Row was read only at the earlier step , and row is written only at the later step . So every read of row sees the value from before the handling of , even when , because the read and the write are always in different rows. Inside one step the reads are in row and the writes in row , so the order of does not matter.
Line L4 takes each with and , so line L5 adds to each entry with , and to no other entry. For the correct second term is 0, and the entry does not change. So $C' = $ the correct table on the range . The loop of line L3 covers the rows from to , and a subset of has at most players, so no size is missed.
One more point needs care: line L5 drops each set of weight or more. This is safe, because a set of weight at least only grows in weight when the later steps add players to it, since the weights are nonnegative. So no entry with ever needs a count of a set of weight or more.
Lemma (swings). After the loop of line L2 ends, line L6 sets to the number of swings of of size : sets with , and .
Proof. At the end, . A set is a swing if and only if , which is since weights are nonnegative. Line L6 adds the entries for exactly these , and by the table lemma each entry counts the sets of size and weight .
Theorem. Line L7 returns the raw Banzhaf index of , and line L8 returns the Shapley-Shubik index of .
Proof. The game is monotone: if then , so . Hence the marginal contribution of to a set is 0 or 1, and it is 1 exactly when is a swing of .
The raw Banzhaf index is the mean of the marginal contribution over the sets , so it is the number of swings divided by . By the swings lemma, this number is , which line L7 uses.
The Shapley-Shubik index is the Shapley value of the simple game. By the subset formula,
The weight depends only on , and the bracket is 1 for the swings and 0 for the other sets. If we group the sets by size, the sum is , which is line L8.
Normalized index. The normalized Banzhaf index divides the swings of 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 or more is a swing for the set of the players before it, and such a player exists because and .
Complexity
- Time per player. Lines L2 to L5 run times over rows and at most columns, so additions. Lines L6 to L8 add more. All players take .
- Banzhaf only. Without the size index, the table is one row of length , filled as in the subset sum counting program, in per player and for all players.
- Space. numbers for the table, or for the Banzhaf index alone.
- Number size. The counts reach , so they have up to bits. On a word RAM with -bit words, each addition costs word operations, which adds this factor to the bounds above. The final fractions have denominators and .
The bounds are pseudo-polynomial: they depend on the value , which can be exponential in the input length. Since , they are polynomial when the weights are bounded by a polynomial in , for example when the weights are seat counts or votes written in unary. The hardness theorem shows that the dependence on 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 are stored, which also bounds the table by and not by .
Variants and improvements
- Deletion instead of recomputation. Build the table once with all players, in time. The table without player follows from it by running line L5 backwards: for upward from 1, . This takes per player, so all Shapley-Shubik indices take in total, and all Banzhaf indices . The truncation at stays valid, because a set of weight with comes from a set of weight without .
- Generating functions. The counts are the coefficients of , where marks the weight and the size. Multiplying the factors one by one is the table above. With fast polynomial multiplication, a product tree speeds up the computation when is large compared with .
- 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 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 , 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 , or line L4 must go down in when there is no size index. An upward loop counts sets that contain player twice, which is the unbounded knapsack and gives wrong counts.
- The window. The lower end is , not , and the upper end is . A player with swings for every losing coalition of the others.
- The quota convention. "More than half of " means . "At least half" is a different game when 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 , which overflows 64-bit integers for . 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 .
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# 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
- 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
- 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)
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag MQFKCA Edit this page History Report an error Markdown