#K54617. Evaluating Valid Mathematical Expressions
Evaluating Valid Mathematical Expressions
Evaluating Valid Mathematical Expressions
You are given a list of mathematical expressions. An expression is considered valid only if it meets the following criteria:
- It contains at least three tokens when split by whitespace.
- The first and the last tokens are non-negative integers.
- The tokens alternate between numbers and operators, where only '+' and '-' are allowed as operators.
Your task is to evaluate each valid expression and output the results in the order they appear. Invalid expressions should be ignored.
Note: All tokens in a valid expression must be separated by a single space and no negative numbers are allowed as an immediate operand.
The evaluation is done using standard arithmetic. For example, the expression 3 + 5 - 2 evaluates to 6.
Formula: A valid expression can be represented as:
$$ n_1 \; op_1 \; n_2 \; op_2 \; n_3 \; \cdots \; op_{k-1} \; n_k $$
where each \( n_i \) is an integer and \( op_i \) is either \( + \) or \( - \).
inputFormat
The first line of input contains an integer \(T\) denoting the number of expressions. The following \(T\) lines each contain a mathematical expression.
Example:
3 3 + 5 - 2 3 + -5 10 + 15 - 5
outputFormat
Output the evaluated results of all valid expressions in order, separated by a single space. If there are no valid expressions, output an empty line.
Example:
6 20## sample
3
3 + 5 - 2
3 + -5
10 + 15 - 5
6 20
</p>