Click4Ai

14.

Medium

Write a function calculate_variance(arr) that calculates the population variance of an array without using np.var().

Population variance = (1/N) * sum((xi - mean)^2)

Example:

Input: arr = [2, 4, 4, 4, 5, 5, 7, 9]

Output: 4.0

**Explanation:** Mean = 5.0, Variance = ((2-5)^2 + (4-5)^2 + (4-5)^2 + (4-5)^2 + (5-5)^2 + (5-5)^2 + (7-5)^2 + (9-5)^2) / 8 = 32/8 = 4.0

Constraints:

  • Array length: 1 <= len(arr) <= 1000
  • Return a float
  • Test Cases

    Test Case 1
    Input: [2, 4, 4, 4, 5, 5, 7, 9]
    Expected: 4.0
    Test Case 2
    Input: [1, 1, 1, 1]
    Expected: 0.0
    Test Case 3
    Input: [1, 2, 3, 4, 5]
    Expected: 2.0
    + 2 hidden test cases