Prepare a feature table

Real data arrives with gaps and text. Turn a small table of ages and cities into numbers a model can use.

What to build

A program that fills missing ages, standardizes them and one-hot encodes the cities.

Requirements

  • Replace each missing age (?) with the median of the known ages (the mean of the two middle ones if their count is even).
  • Standardize the ages: z = (age − mean) / σ, with the population σ of the filled ages. If σ is 0, every z is 0.
  • Print a header age followed by the cities in alphabetical order.
  • Then one row per person: z with 2 decimal places, then a 1 in their city's column and 0 elsewhere.

Input

Line 1: n. Then n lines age city, where the age is a number or ?.

Output

The header, then n rows.

Constraints

1 ≤ n ≤ 500; at least one age is known; cities are single words.

Example

Input:

4
20 Dhaka
? Sylhet
40 Dhaka
30 Khulna

Output:

age Dhaka Khulna Sylhet
-1.41 1 0 0
0.00 0 0 1
1.41 1 0 0
0.00 0 1 0

Why it works

Filling gaps with the median keeps every row without inventing extreme values, standardizing puts the ages on a common scale, and one-hot columns turn each city into numbers without inventing an order.

Examples

Example 1 · Input
4
20 Dhaka
? Sylhet
40 Dhaka
30 Khulna
Expected output
age Dhaka Khulna Sylhet
-1.41 1 0 0
0.00 0 0 1
1.41 1 0 0
0.00 0 1 0
Example 2 · Input
2
10 A
20 B
Expected output
age A B
-1.00 1 0
1.00 0 1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Find the median of the known ages first, then replace every `?` with it.

Hint 2

Standardize the filled ages: z = (age − mean) / σ with σ dividing by n; if σ is 0, every z is 0.

Hint 3

The one-hot columns are the different cities in alphabetical order.

Solution

Show one correct solution (try it yourself first)
n = int(input())
rows = [input().split() for _ in range(n)]
known = sorted(float(a) for a, _ in rows if a != "?")
m = len(known)
median = known[m // 2] if m % 2 else (known[m // 2 - 1] + known[m // 2]) / 2
ages = [median if a == "?" else float(a) for a, _ in rows]
mean = sum(ages) / n
std = (sum((a - mean) ** 2 for a in ages) / n) ** 0.5
cities = sorted({city for _, city in rows})
print("age", *cities)
for age, (_, city) in zip(ages, rows):
    z = (age - mean) / std if std > 0 else 0.0
    print(f"{z:.2f}", *[1 if c == city else 0 for c in cities])

Lesson: Data, statistics and features →