PIXELBANKv9.1.0
Menu

Implement top-p (nucleus) sampling from a probability distribution.

Nucleus sampling selects the smallest set of tokens whose cumulative probability exceeds a threshold p, then renormalizes.

Algorithm:

  1. Sort tokens by probability (descending)
  2. Compute cumulative probabilities
  3. Find the smallest set of tokens where cumulative probability >= p
  4. Renormalize the selected probabilities to sum to 1

Since we need deterministic output, return the renormalized probability distribution (with non-selected tokens set to 0).

Input format:

  • Line 1: p threshold (float, 0 < p <= 1)
  • Line 2: Token names (space-separated)
  • Line 3: Corresponding probabilities (space-separated floats, sum to 1)

Output: A dictionary of token: renormalized_probability for selected tokens (prob > 0), sorted by probability descending. Round to 4 decimal places.

Example:

Input:
0.8
the a an this that
0.35 0.25 0.20 0.15 0.05
Output:
{'the': 0.4375, 'a': 0.3125, 'an': 0.25}
Reasoning:

Step 1: Sort by probability (already sorted) the: 0.35, a: 0.25, an: 0.20, this: 0.15, that: 0.05

Step 2: Cumulative probabilities the: 0.35 the + a: 0.60 the + a + an: 0.80 >= 0.8 => STOP

Step 3: Selected tokens: {the, a, an} with probs [0.35, 0.25, 0.20]

Step 4: Renormalize Sum = 0.80 the: 0.35/0.80 = 0.4375 a: 0.25/0.80 = 0.3125 an: 0.20/0.80 = 0.25

Constraints:

  • Include the minimum number of tokens to reach cumulative prob >= p
  • Renormalize selected probabilities to sum to 1
  • Round to 4 decimal places
  • Output only tokens with non-zero probability
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Nucleus Sampling - Hard | PixelBank