Sample Variance and Bessel's Correction

~10 mincode completion

Implement sample_variance(x, ddof) from the definition, dividing by . Do not call .

Examples

Three points, dividing by n

Input
sample_variance([2, 4, 6], 0)
Output
2.66667

The same three points, corrected for the estimated mean

Input
sample_variance([2, 4, 6], 1)
Output
4

Identical observations have no spread either way

Input
sample_variance([5, 5, 5, 5], 1)
Output
0

Hints

Hint 1

Sum with , and check which axis you are summing over.

Hint 2

A common slip here: hardcodes n instead of n - ddof.

Requirements

  • x: array of observations, shape (n,)

  • : delta degrees of freedom. 0 divides by n, 1 divides by n-1.

  • Return float

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~10 min

8 employers weight this skill

4 quant funds, 2 health and bio companies, 2 big tech firms. Top match scores 93.

Python
import numpy as np


def sample_variance(x, ddof):
    """
    Variance of a sample, with an adjustable denominator.

    Args:
        x:    array of observations, shape (n,)
        ddof: delta degrees of freedom. 0 divides by n, 1 divides by n-1.

    Returns:
        float
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.