Neural Mastery
← Practice
Decision Tree Gini Impurityeasy

Decision Tree Gini Impurity

easy Classical ML from Scratch 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Calculate the Gini impurity metric for a set of categorical target labels.

Related Skills

Task

Implement gini_impurity(labels): compute Gini impurity 1.0 - sum((count_k / N)**2). Return 0.0 for empty input. Round float to 4 decimal places.

Function Signature

gini_impurity(labels: list[any]) -> float

Examples

Example 1: Equal binary classes gives 0.5
Input: labels = [0, 0, 1, 1]
Output: 0.5
Example 2: Pure single class gives 0.0
Input: labels = ['cat', 'cat', 'cat']
Output: 0

Constraints

  • labels is a list of hashable elements
Python3Saved ✓
def gini_impurity(labels: list[any]) -> float:
"""Compute Gini impurity for class label list.
Round float to 4 decimal places. Empty list returns 0.0.
"""
pass

Case 1: Equal binary classes gives 0.5
Input: labels = [0, 0, 1, 1]
Expected: 0.5
Case 2: Pure single class gives 0.0
Input: labels = ['cat', 'cat', 'cat']
Expected: 0