Skip to content
DeepForgeby svx
All problems
MediumProbabilitypr-215

Inverse Transform Discrete Counts

Problem

Generate n samples from a discrete distribution by inverse transform with random.Random(seed). For each uniform u, return the first index whose cumulative probability exceeds u, and count the results. Return [] for an empty distribution or n <= 0.

Hint

Walk the cumulative distribution and pick the first crossing index.

Test cases

case 1
in: [[0.5,0.5],1000,42]
expected: [480,520]
case 2
in: [[0.3333333333333333,0.3333333333333333,0.3333333333333333],600,7]
expected: [218,190,192]
case 3
in: [[1],50,1]
expected: [50]
case 4
in: [[],5,0]
expected: []
Starter codePython
import random


def inverse_transform_discrete(probs, n, seed):
    # Your code here
    pass

4 test cases · run your code against them in the editor