Data science: Count an ordered category

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: COUNT for 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; print median: none if 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

Example 1 · Input
S M L XL
6
M
L
S
M
XL
M
Expected output
S: 1
M: 3
L: 1
XL: 1
median: M
Example 2 · Input
low medium high
4
high
HIGH
low
medium
Expected output
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")

Lesson: Data types and tables →