Ctrl K

Grading the Arithmetic Quiz

Hard
A teacher gave the class the expression expression: single-digit numbers separated by + and * signs, such as 4+2*3. It has to be evaluated by the usual rules: first all multiplications from left to right, then all additions from left to right. The students' answers are collected in the array answers, in no particular order. Each answer is graded as follows: - **5 points** if it equals the correct value of the expression; - otherwise **2 points** if that number can be obtained by doing the operations in some other order, that is, by placing brackets in the expression some other way, with no arithmetic mistakes; - otherwise **0 points**. Return the total number of points earned by all students.
Example 1
expression="4+2*3", answers=[10, 18, 10, 7, 0] → 12

The right value is 4 + 2·3 = 10, so two students get 5 points each. 18 comes from adding first, (4 + 2)·3, which earns 2 points. Neither 7 nor 0 can be obtained with any brackets. Total: 5 + 2 + 5 = 12.

Example 2
expression="2*3+1*4", answers=[10, 14, 32, 9] → 9

The right answer is 10. Other orders of operations give 14 = 2·(3 + 1·4), 28 = (2·3 + 1)·4 and 32 = 2·(3 + 1)·4, so 14 and 32 earn 2 points each and 9 earns nothing. Total: 9.

Example 3
expression="3+0*1", answers=[3, 3, 0] → 10

(3 + 0)·1 is also 3, but the answer matches the right one, so it still earns 5 points, not 2. The answer 0 is unreachable. Total: 10.

Constraints
  • 3 ≤ len(expression) ≤ 31
  • expression is a valid expression: digits from 0 to 9 alternating with + and * signs, starting and ending with a digit
  • The correct value of the expression is between 0 and 1000
  • 1 ≤ len(answers) ≤ 10⁴
  • 0 ≤ answers[i] ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEvery Way to Space the Words HardClear the Marble Row HardNumbers From Working Keys HardOther Orders for the Same Search Tree HardMouse, Cat and Cheese Hard
loading Python…
Input
expression="4+2*3", answers=[10, 18, 10, 7, 0]
Expected
12

Run checks the first 3 tests in your browser. Submit checks all 108 tests on the server, hidden ones included.