Measure the disorder (entropy) in apple colors. Given a collection of items with categorical labels (e.g., apple colors: red, green, yellow), calculate the Shannon entropy to quantify the impurity or disorder of the distribution.
import math
from collections import Counter
def entropy(labels: list) -> float:
n = len(labels)
if n == 0:
return 0.0
counts = Counter(labels)
h = 0.0
for count in counts.values():
p = count / n
if p > 0:
h -= p * math.log2(p)
return round(h, 4)H = -sum(p_i * log2(p_i)) for all categories.log2(k) when items are uniformly distributed across k classes.