Ordinal categories have an order that the alphabet does not know. Count them and find their median using the order you are given.
What to build
A program that counts the values of an ordinal variable and finds its median.
Requirements
- Print
LEVEL: COUNTfor every level, in the given order, even when the count is 0. - If some values are not one of the levels (matching is case-sensitive), print
unknown: K. - Print
median: LEVEL: sort the known values by level order and take the one at position (m − 1) // 2, where m is how many there are; printmedian: noneif there are none.
Input
Line 1: the levels in order, separated by spaces. Line 2: n. Then n values, one per line.
Output
The counts, perhaps the unknown line, then the median.
Constraints
1 ≤ n ≤ 1000; 2 to 10 levels.
Example
Input:
S M L XL
6
M
L
S
M
XL
M
Output:
S: 1
M: 3
L: 1
XL: 1
median: M
Why it works
The median of an ordinal variable is meaningful because its values can be put in order, but only with the order the data comes with, so sorting by position in the level list rather than by spelling is the key step.
Examples
S M L XL 6 M L S M XL M
S: 1 M: 3 L: 1 XL: 1 median: M
low medium high 4 high HIGH low medium
low: 1 medium: 1 high: 1 unknown: 1 median: medium
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Use the position in the list of levels as the sort key: levels.index(value).
Hint 2
Leave unknown values out of the sorted list before taking the median.
Solution
Show one correct solution (try it yourself first)
levels = input().split()
n = int(input())
values = [input() for _ in range(n)]
for level in levels:
print(level + ":", values.count(level))
unknown = [v for v in values if v not in levels]
if unknown:
print("unknown:", len(unknown))
known = sorted((v for v in values if v in levels), key=levels.index)
if known:
print("median:", known[(len(known) - 1) // 2])
else:
print("median: none")