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:
Test Cases
Test Case 1
Input:
[0, 0, 0, 0]Expected:
0.0Test Case 2
Input:
[0, 1, 0, 1]Expected:
0.5Test Case 3
Input:
[0, 1, 2]Expected:
0.6666666666666667+ 2 hidden test cases