Apply type rules to a single operation.
What to build
A program that gives the type of A OP B, where A and B are literals, or reports a type error.
Requirements
- Types:
int(12),float(1.5),str("word"),bool(true, false). - Rules:
+ - *on two numbers give int if both are int, otherwise float;+on two strings gives str;/on two numbers gives float;<on two numbers gives bool;==gives bool for two numbers or two values of the same type;and,oron two bools give bool. Anything else:type error: cannot apply OP to T1 and T2.
Input
One line: a literal, an operator and a literal, separated by spaces. Strings contain no spaces.
Output
One line: a type, or the error.
Constraints
Numbers are not negative.
Example
Input:
1 + 2
Output:
int
Why it works
A type rule looks only at the operator and the types of its operands, never at their values.
Examples
Example 1 · Input
1 + 2
Expected output
int
Example 2 · Input
1 + "a"
Expected output
type error: cannot apply + to int and str
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Find the type of each literal first: true/false, a quoted string, a number with a dot, or a whole number.
Hint 2
Then apply the rules in order; anything not covered is a type error.
Solution
Show one correct solution (try it yourself first)
a, op, b = input().split()
def type_of(token):
if token in ("true", "false"):
return "bool"
if token.startswith('"'):
return "str"
return "float" if "." in token else "int"
ta, tb = type_of(a), type_of(b)
numbers = ta in ("int", "float") and tb in ("int", "float")
result = None
if op in "+-*" and numbers:
result = "int" if ta == tb == "int" else "float"
elif op == "+" and ta == tb == "str":
result = "str"
elif op == "/" and numbers:
result = "float"
elif op == "<" and numbers:
result = "bool"
elif op == "==" and (numbers or ta == tb):
result = "bool"
elif op in ("and", "or") and ta == tb == "bool":
result = "bool"
print(result or f"type error: cannot apply {op} to {ta} and {tb}")