Data science: Melt a wide table

Turn a wide table into tidy long form, one row per measurement.

What to build

A program that melts a wide table.

Requirements

  • The first column identifies each row. For each row, in order, and each other column, in header order, print ID,COLUMN,VALUE, skipping empty values.
  • Finally print long rows: K.

Input

Line 1: the header, separated by commas. Line 2: n. Then n rows separated by commas.

Output

The long rows, then the count.

Constraints

1 ≤ n ≤ 100; 2 to 13 columns; no quoting.

Example

Input:

student,math,physics
2
Asha,80,75
Ben,65,

Output:

Asha,math,80
Asha,physics,75
Ben,math,65
long rows: 3

Why it works

Every measurement becomes a row with its identifier and its variable's name, so later steps can group by any of the three columns with the same simple code.

Examples

Example 1 · Input
student,math,physics
2
Asha,80,75
Ben,65,
Expected output
Asha,math,80
Asha,physics,75
Ben,math,65
long rows: 3
Example 2 · Input
city,2023,2024
1
Dhaka,10.2,10.4
Expected output
Dhaka,2023,10.2
Dhaka,2024,10.4
long rows: 2

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

Hints

Hint 1

The first column is the identifier; every other column becomes a row of (identifier, column, value).

Hint 2

Skip empty values, and count the rows you print.

Solution

Show one correct solution (try it yourself first)
header = input().split(",")
n = int(input())
count = 0
for _ in range(n):
    values = input().split(",")
    for column, value in zip(header[1:], values[1:]):
        if value != "":
            print(f"{values[0]},{column},{value}")
            count += 1
print("long rows:", count)

Lesson: Tidy data: reshaping tables →