32. KL divergence
kl_divergence()Asked in screens shaped like: DeepMind, Two Sigma
Kullback–Leibler divergence KL(p || q) in nats: sum p_i log(p_i / q_i). Skip zeros in p. Assume q_i > 0 wherever p_i > 0. Round to 4 decimals.
Examples
Example 1
Input: { "p": [0.5, 0.5], "q": [0.9, 0.1] } Output: 0.5108
Constraints
- p and q are the same length, non-negative, and q > 0 wherever p > 0
Implement kl_divergence(). Types below are the NumPy contract; Python and PyTorch use lists or tensors with the same names.
| Name | Type | I/O |
|---|---|---|
| p | array | Input |
| q | array | Input |
| value | float | Output |
Same tests, three APIs. Pick a language with the chips above the editor.
NumPy
Vectorized arrays. Default for analyst, scientist, and DE screens.
Revealed one at a time. The reference implementation stays in the Solution tab.
Hint 1
Keep the function signature. Fill the body — do not rename parameters.
Hint 2
Match the rounding in the examples. Tests compare with a small numeric tolerance.
Hint 3
Switch NumPy / Python / PyTorch with the chips above the editor. Each language has its own tests.
Run your code to see stdout.
Submit to run the checks.
All tests passed on this language.
Next problem: Huber loss →Pro problem
Hard problems unlock with Pro
Easy pads stay free. Medium and hard SQL and Python problems — editor, tests, hints, and solutions — open after you upgrade to Pro or coaching.
See plansPractice free easy problems