The Gini index measures how mixed a group of examples is: 0 when every example has the same class.
What to build
A program that computes the Gini impurity of a group from its class counts.
Requirements
- Print
gini Gwith 3 decimal places.
Input
One line of class counts (non-negative integers).
Output
One line.
Constraints
1 to 50 counts; their total is at least 1.
Example
Input:
5 5
Output:
gini 0.500
Why it works
Σ p² is the chance that two examples drawn at random share a class, so 1 − Σ p² is the chance they differ: 0 for a pure group, larger the more mixed it is.
Examples
Example 1 · Input
5 5
Expected output
gini 0.500
Example 2 · Input
10 0
Expected output
gini 0.000
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Divide each count by the total to get the class shares p.
Hint 2
Gini = 1 − Σ p².
Solution
Show one correct solution (try it yourself first)
counts = list(map(int, input().split()))
total = sum(counts)
print(f"gini {1 - sum((c / total) ** 2 for c in counts):.3f}")