Expression Evaluator
InterviewTime limit1sMemory limit128 MB
Evaluate a C-style expression of letter variables with binary + and -, plus pre and post ++ and --, then report the result and each used variable's final value.
- Level
Medium4 of 10
- Topics
- String, Simulation, Implementation, Array
- Solved
- No attempts yet
Problem
This problem is about evaluating simple C-style expressions. Each expression contains only integer variables and a limited set of operators; there are no numeric constants.
There are 26 variables, named by the lowercase letters a through z. Before an expression is evaluated, the variables hold their initial values a = 1, b = 2, ..., z = 26.
The binary operators + and - (addition and subtraction) are allowed, with their usual meaning. For example, the expression a + c - d + b has the value .
The unary operators ++ and -- are also allowed. They may appear immediately before a variable (pre-increment / pre-decrement) or immediately after it (post-increment / post-decrement).
- If
++appears before a variable, that variable is increased by one before its value is used in the expression. Thus++c - bhas the value . - If
++appears after a variable, that variable is increased by one after its value is used. Thusc++ - bhas the value , andcbecomes4afterwards. - The
--operator works the same way but decreases the variable by one.
Formally, an expression is evaluated as follows:
- For every variable preceded by
++(or--), record an assignment that increments (or decrements) it, and remove that operator from before the variable. - Do the same for every variable followed by
++(or--). - No unary operator now remains; record a statement that evaluates the remaining expression.
- Execute the statements from step 1 first, then the statement from step 3, and finally the statements from step 2.
For example, evaluating ++a + b++ is the same as computing a = a + 1, then result = a + b, then b = b + 1.
Input
The first line contains a single integer , the number of test cases, followed by lines, each containing one input expression.
Ignore any blanks inside an expression. Every input expression is unambiguous (for example, a+++b never appears). A single variable never has a unary operator both before and after it (for example, ++a++ never appears). You may assume each variable appears at most once in an expression.
Output
For each test case, print the expression as it appears in the input, with blanks removed, on a line beginning with Expression: . On the following line print value = followed by the value of the whole expression.
Then print the final value of each variable used in the expression, one per line, in the form <variable> = <value>, sorted alphabetically by variable name. Print only the variables that actually appear in the expression.