Click4Ai

75.

Easy

Write a function gini_impurity(y) that computes the Gini impurity of a label array. Gini impurity measures how often a randomly chosen element would be incorrectly classified if it were labeled according to the distribution of labels in the set.

**Formula:** Gini = 1 - sum(p_i^2) where p_i is the proportion of class i in the array.

Example:

Input: y = [0, 1, 0, 1]

Output: 0.5

**Explanation:** There are 2 classes (0 and 1), each with proportion 0.5. Gini = 1 - (0.5^2 + 0.5^2) = 1 - 0.5 = 0.5

Constraints:

  • y is a 1D numpy array of integer class labels
  • Return a float between 0.0 (pure) and 1.0 (maximally impure)
  • A pure array (all same label) should return 0.0
  • Test Cases

    Test Case 1
    Input: [0, 0, 0, 0]
    Expected: 0.0
    Test Case 2
    Input: [0, 1, 0, 1]
    Expected: 0.5
    Test Case 3
    Input: [0, 1, 2]
    Expected: 0.6666666666666667
    + 2 hidden test cases