Data science: Tidy a messy column

A column holds a city and a year joined by a hyphen, and another holds a list of tags. Tidy both.

What to build

A program that splits combined columns and gives each tag its own row.

Requirements

  • Split place_year at its last hyphen into a city and a year.
  • Split tags at semicolons, remove spaces around each tag, drop empty tags and repeats within the row (keep the first; matching is case-sensitive). If no tags remain, use the tag none.
  • Print the header id,city,year,tag, one row per tag in input order, then rows: K.

Input

Line 1: n. Then n lines id,place_year,tags.

Output

The header, the rows, then the count.

Constraints

1 ≤ n ≤ 500; ids and place names contain no commas.

Example

Input:

2
1,Dhaka-2021,food; travel
2,Sylhet-2022,

Output:

id,city,year,tag
1,Dhaka,2021,food
1,Dhaka,2021,travel
2,Sylhet,2022,none
rows: 3

Why it works

After splitting, every cell holds one value and every row one observation, so counting tags or grouping by city or year becomes a simple loop, and splitting at the last hyphen keeps hyphenated names intact.

Examples

Example 1 · Input
2
1,Dhaka-2021,food; travel
2,Sylhet-2022,
Expected output
id,city,year,tag
1,Dhaka,2021,food
1,Dhaka,2021,travel
2,Sylhet,2022,none
rows: 3
Example 2 · Input
1
9,Cox's-Bazar-2020,beach;beach;sun
Expected output
id,city,year,tag
9,Cox's-Bazar,2020,beach
9,Cox's-Bazar,2020,sun
rows: 2

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

Hints

Hint 1

rsplit("-", 1) splits at the last hyphen, so a city name with hyphens stays whole.

Hint 2

Split the tags at ";", strip each, drop empty ones and repeats, and print one row per tag (or "none").

Solution

Show one correct solution (try it yourself first)
n = int(input())
rows = []
for _ in range(n):
    rid, place_year, tags = input().split(",", 2)
    city, year = place_year.rsplit("-", 1)
    kept = []
    for tag in tags.split(";"):
        tag = tag.strip()
        if tag and tag not in kept:
            kept.append(tag)
    for tag in kept or ["none"]:
        rows.append(f"{rid},{city},{year},{tag}")
print("id,city,year,tag")
for row in rows:
    print(row)
print("rows:", len(rows))

Lesson: Tidy data: reshaping tables →