The simplest aggregation is a count. Count each category and its share of the total.
What to build
A program that counts the values of a categorical column.
Requirements
- Print
CATEGORY: COUNT (P%)for each category, where P is its share of all values to one decimal. - Order the lines by count from highest, and equal counts alphabetically (matching is case-sensitive).
Input
Line 1: n. Then n values, one per line.
Output
One line per category.
Constraints
1 ≤ n ≤ 10000.
Example
Input:
5
tea
coffee
tea
juice
tea
Output:
tea: 3 (60.0%)
coffee: 1 (20.0%)
juice: 1 (20.0%)
Why it works
A count per category with its percentage is the basic summary of a categorical variable, and sorting by count with a name tie-break puts the most common categories first in a fixed order.
Examples
Example 1 · Input
5 tea coffee tea juice tea
Expected output
tea: 3 (60.0%) coffee: 1 (20.0%) juice: 1 (20.0%)
Example 2 · Input
2 b a
Expected output
a: 1 (50.0%) b: 1 (50.0%)
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
collections.Counter counts the values in one line.
Hint 2
Sort the items with key=lambda item: (-item[1], item[0]).
Solution
Show one correct solution (try it yourself first)
from collections import Counter
n = int(input())
counts = Counter(input() for _ in range(n))
for value, count in sorted(counts.items(), key=lambda item: (-item[1], item[0])):
print(f"{value}: {count} ({100 * count / n:.1f}%)")