Practice/Meta/Evaluate and Simplify Mathematical Expressions
CodingMust
Build a system that can parse and evaluate mathematical expressions containing numbers, variables, operators, and parentheses. Your implementation should respect standard mathematical operator precedence rules and correctly handle nested parentheses.
You need to implement a function that takes a mathematical expression as a string and a dictionary of variable values, then returns the evaluated numeric result as a string.
The expression will contain:
x, abc, value1)+ (addition), - (subtraction), * (multiplication), / (division)( and )1 <= expression.length <= 1000+, -, *, /, parentheses, variables, and spaces-5)0 <= variables.size <= 100[-10000, 10000]Example 1:
Input: expression = "3 + 5 * 2", variables = \{\} Output: "13" Explanation: Multiplication has higher precedence than addition, so we compute 5 * 2 = 10 first, then 3 + 10 = 13.
Example 2:
Input: expression = "(3 + 5) * 2", variables = \{\} Output: "16" Explanation: Parentheses have highest precedence. We evaluate 3 + 5 = 8 first, then 8 * 2 = 16.
Example 3:
Input: expression = "x + y * 2", variables = \{"x": 10, "y": 5\} Output: "20" Explanation: Substitute variables: "10 + 5 * 2". Then evaluate: 5 * 2 = 10, then 10 + 10 = 20.
Example 4:
` Input: expression = "((a + b) * c - d) / e", variables = {"a": 2, "b": 3, "c": 4, "d": 5, "e": 3} Output: "5.0" Explanation: Work from innermost parentheses outward: