#C13801. Validate Mathematical Equations
Validate Mathematical Equations
Validate Mathematical Equations
You are given a set of mathematical equations represented as strings. Your task is to design a program that checks whether each equation is valid according to the following criteria:
- The equation must only contain digits, the decimal point, arithmetic operators (+, -, *, /), parentheses
( )
, and spaces. - Parentheses must be properly opened and closed, and nested correctly. In LaTeX, this condition is represented as: \(\text{for every opening } ( \text{ there is a matching } )\).
- The equation should not start or end with an operator. That is, the first and last non-space characters should not be any of \(+, -, *, /\).
- No two operators should appear consecutively unless they are separated by a valid parenthesized expression. For example,
3++2-1
is invalid, and so is(1+2)*-3
. - Both integers and floating point numbers are allowed as operands.
Your program will read an integer n
from standard input, followed by n
lines where each line is a mathematical equation. For each equation, output True
if it meets all the criteria above, otherwise output False
. Each result should be printed on a new line.
inputFormat
The input is read from stdin
and has the following format:
n equation_1 equation_2 ... equation_n
Here, n
is an integer that denotes the number of equations to validate. Each subsequent line contains one equation as a string.
outputFormat
For each equation provided in the input, output either True
or False
(each on a new line) to stdout
indicating whether the equation is valid according to the criteria described in the problem statement.
4
3+2-1
(1+2)*3
3*(2+1)
2.5+3.1
True
True
True
True
</p>