#C14351. Evaluate Mathematical Expressions

    ID: 43991 Type: Default 1000ms 256MiB

Evaluate Mathematical Expressions

Evaluate Mathematical Expressions

You are given a list of mathematical expressions in string format. Your task is to determine the validity of each expression. An expression is considered valid if it can be correctly evaluated without encountering any errors (such as syntax errors or division by zero) following the standard arithmetic operations.

The expressions may contain integers, the four basic arithmetic operators +, -, *, /, and parentheses. Note that:

  • If an expression contains division by zero, it is invalid.
  • If an expression has unmatched parentheses or a syntax error, it is invalid.
  • Empty expressions are considered invalid.

You may implement your solution using a recursive descent parser or any built‐in evaluation function available in your language, making sure to catch exceptions or errors appropriately.

For example, a valid expression such as (1 + 2) * 3 should evaluate successfully, whereas expressions like 1 / 0 or 3 + 2 * are invalid.

The grammar of a valid expression roughly follows the rules below:

ET  ((\+)  T)E \to T \; ((\+|-) \; T)^* TF  ((\*/)  F)T \to F \; ((\*|/) \; F)^* F(E)    numberF \to (E) \;|\; \text{number}

inputFormat

The first line contains a single integer T (1 ≤ T ≤ 100), representing the number of expressions. Each of the following T lines contains one mathematical expression as a string.

outputFormat

Output exactly T lines. The i-th line should be 'True' (without quotes) if the i-th expression is valid, and 'False' otherwise.## sample

4
1 + 1
3 * (2 + 1)
10 / 2
(5 + 3) * 2
True

True True True

</p>