Fix the formula evaluator that still calls eval
Your task
Your product has a custom formula feature: users type a math expression and the server computes it. The first version passed the text straight to eval, so a "formula" could run any code on the server. The fix must accept arithmetic and nothing else.
An assistant wrote evaluate_expression(expression). It is in the editor. It has a bug. Find it and fix it.
Input and output:
expression: the text the user typed.- Return
[value], a list holding the integer result, or[]when the text is not an expression this feature accepts. An empty list is the rejection, because any integer,-1included, can be a real result.
Rules the tests check:
- The only characters allowed are the digits 0 to 9, the space,
+,-,*,(and). Anything else returns[]. - A number is a run of digits, so numbers are whole and never negative. Leading zeros are fine:
007is 7. - Spaces may go anywhere between numbers, operators and parentheses. They are ignored, except that they end a number.
- The grammar is strict, and there is no implied multiplication:
- A number or
(may only come first, or right after an operator or(. So2 3,2(3),(2)3and(2)(3)are rejected. - An operator (
+,-or*) or)may only come right after a number or). So-5,2 ** 3and()are rejected. - The expression must end with a number or
), so2 +is rejected. An empty expression, or one with only spaces, is rejected too. - Parentheses must balance: every
)closes an earlier(that is still open, and every(is closed. So(2))+(3is rejected.
- A number or
*comes before+and-.+and-rank the same and work from left to right, so10 - 2 - 3is 5.
Examples:
evaluate_expression("2 * (3 + 4)")returns[14].evaluate_expression("require('child_process')")returns[].evaluate_expression("10 - 2 - 3")returns[5].
Then, in a sentence or two: how would you catch this kind of bug in review?
Examples
evaluate_expression(expression: str) -> list[int]Example 1
Input
evaluate_expression("2 * (3 + 4)")Output
[14]Example 2
Input
evaluate_expression("require('child_process')")Output
[]Example 3
Input
evaluate_expression("10 - 2 - 3")Output
[5]