DataLane

32. KL divergence

hardProNot started~14 minPythonImplement 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

Python editor

Loading Python engine…

Ctrl/Cmd + Enter submits

Run your code to see stdout.

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
↑↓ navigate openesc close