Values read from a file are all text. Work out which columns really hold whole numbers, decimals or text.
What to build
A program that infers the type of each column of a table.
Requirements
- For each column, in header order, print
NAME: integerif every value is a whole number (digits with an optional minus sign),NAME: decimalif not but every value converts withfloat(), andNAME: textotherwise.
Input
Line 1: the header, column names separated by commas. Line 2: n. Then n rows of values separated by commas (no quoting, no empty values).
Output
One line per column.
Constraints
1 ≤ n ≤ 100; 1 to 10 columns.
Example
Input:
name,age,height,city
3
Asha,34,1.62,Dhaka
Ben,29,1.80,Sylhet
Chen,41,1.75,Khulna
Output:
name: text
age: integer
height: decimal
city: text
Why it works
Checking every value, not just the first, matters because a single text value such as "three" makes a whole column text, and finding that out before analysing it avoids crashes and wrong averages later.
Examples
name,age,height,city 3 Asha,34,1.62,Dhaka Ben,29,1.80,Sylhet Chen,41,1.75,Khulna
name: text age: integer height: decimal city: text
id,score 2 1,90 2,87.5
id: integer score: decimal
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
re.fullmatch(r"-?\d+", value) tells you whether a value is a whole number.
Hint 2
Try float(value) for every value inside try ... except ValueError.
Solution
Show one correct solution (try it yourself first)
import re
header = input().split(",")
n = int(input())
rows = [input().split(",") for _ in range(n)]
def kind(values):
if all(re.fullmatch(r"-?\d+", v) for v in values):
return "integer"
try:
for v in values:
float(v)
return "decimal"
except ValueError:
return "text"
for i, name in enumerate(header):
print(name + ": " + kind([row[i] for row in rows]))