Projects · 17 / 19 Exercise Hard

Calculator with a parser

Objective

A real calculator does not use eval: it parses the expression. Split the text into tokens and write one function per precedence level (addition and subtraction, product and division, power, parentheses and numbers).

Instructions

  • The first line has the number n of expressions; then one per line, with numbers (with or without decimals), +, -, *, /, ^, parentheses, spaces and a minus sign before a number or parenthesis.
  • Precedence: ^ is the highest and groups from the right (2^3^2 is 512); unary minus is below ^ (-2^2 is -4); then * and /, and finally + and -, both left to right.
  • Show the result as an integer if it is one, or rounded to 4 decimals. If the expression is not valid or divides by zero, show Error. Do not use eval or exec.
Input
4
1 + 2 * 3
(1 + 2) * 3
2^3^2
10 / 4
Output
7
9
512
2.5

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise