LearnCoding

Sampling indices from a weighted (multinomial) distribution

EasySampling, Binary search

Problem

Weights are non-negative with a positive total. For each u in us (each in [0, 1)), return the smallest index i whose cumulative weight cum[i] > u·total. Raise ValueError for a negative weight or an all-zero total. Aim for O(n) setup and O(log n) per draw.

Signature

def sample_indices(weights: list[float], us: list[float]) -> list[int]: ...

Examples

The visible tests, as an interactive Python session would show them: each call and the value it should give.

>>> sample_indices([1, 1, 2], [0.0, 0.24, 0.25, 0.49, 0.5, 0.999]) == [0, 0, 1, 1, 2, 2]
True

>>> sample_indices([0, 3, 0, 1], [0.0, 0.5, 0.75, 0.9]) == [1, 1, 3, 3]
True

Solve it in your own editor; nothing on this page runs code.

Hints

Prefix-sum the weights; for each u find the first index with cum[i] > u * total via bisect_right.

Raise ValueError for a negative weight or an all-zero total.

Zero-weight items are never selected — bisect_left is the trap.

Reference solution

import bisect

def sample_indices(weights, us):
    cum = []
    s = 0.0
    for w in weights:
        if w < 0:
            raise ValueError("negative weight")
        s += w; cum.append(s)
    if s == 0:
        raise ValueError("all-zero weights")
    return [bisect.bisect_right(cum, u * s) for u in us]

What a strong solution covers

  • Prefix sums plus bisect_right, so zero-weight items are never selected.
  • Validates inputs.
  • Discusses the alias method (O(1) per draw), numerical drift in prefix sums, and Gumbel-max sampling.

Common mistakes

  • bisect_left, which can select zero-weight items at boundaries
  • linear scans per draw.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.