문제
Decision trees split data into groups that are as pure as possible. Gini impurity measures how mixed a group's labels are:
Gini = 1 - Σ pₖ²
where pₖ is the fraction of labels equal to class k. A group with a single class has impurity 0; an even mix of two classes has impurity 0.5.
Implement gini_impurity(labels).
Input
labels: The class labels in the group.
Output
Return the Gini impurity as a decimal number.
제약 조건
1 ≤ length ≤ 10,000
Each label is 1 to 20 characters
예시
입력:
labels = ["yes", "yes", "no", "no"]
예상 출력:
expected = 0.5
입력:
std::vector<std::string> labels = {"yes", "yes", "no", "no"};
예상 출력:
double expected = 0.5;
입력:
string[] labels = new string[] {"yes", "yes", "no", "no"};
예상 출력:
double expected = 0.5;
설명
Half are yes and half are no: 1 - (0.5² + 0.5²) = 1 - 0.5 = 0.5, the most mixed a two-class group can be.
입력:
labels = ["cat", "cat", "cat"]
예상 출력:
expected = 0.0
입력:
std::vector<std::string> labels = {"cat", "cat", "cat"};
예상 출력:
double expected = 0.0;
입력:
string[] labels = new string[] {"cat", "cat", "cat"};
예상 출력:
double expected = 0.0;
설명
Only one class: 1 - 1² = 0. The group is pure.
참고 자료
이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.