Challenge: Build a mini calculator
Arjun's little sister has maths homework, and Arjun has a plan: a calculator where you type the whole sum, like 2 + 3 * 4, and get the answer. The catch is that a calculator that just goes left to right gets it wrong:
2 + 3 * 4 left to right: 5 * 4 = 20 wrong
maths rules: 2 + 12 = 14 right
Multiplication and division happen before addition and subtraction, and brackets come before everything.
Your task
Write calculate(expression). It takes a sum as text and returns its value as a number.
calculate("2 + 3 * 4") # 14
calculate("10 - 4 - 3") # 3
calculate("7 / 2") # 3.5
calculate("(2 + 3) * 4") # 20
calculate("((1 + 2) * (3 + 4)) - 1") # 20
calculate("2*3+4") # 10
Rules
- Numbers are whole numbers, 0 or more, and can have several digits (
120). There are no negative numbers like-5. - The operators are
+,-,*and/. Division is normal division, so7 / 2is3.5(an answer like1.0is fine where1is expected). *and/come before+and-. Operators at the same level work left to right:10 - 4 - 3is 3.- Brackets
( )can be nested as deep as you like. - Spaces may appear anywhere, or not at all.
- Every sum you get is valid, and nothing is divided by zero.
- No
evalorexec: the point is to do the maths yourself!
Tips
- Step 1, tokens. Turn
"12+(3*4)"into a list:[12, "+", "(", 3, "*", 4, ")"]. Collect digits that are next to each other into one number, and skip spaces. - Step 2, three small functions that each take the tokens and a position, and return the value they read and the position after it, as a tuple
(value, pos):read_expression(tokens, pos)reads a term, then while the next token is+or-, reads another term and adds or subtracts it.read_term(tokens, pos)does the same with factors and*or/.read_factor(tokens, pos)reads a number, or, if the token is(, reads a whole expression and then skips the).
- Because expressions call terms and terms call factors, multiplication is always finished before addition. And because a factor can call an expression, brackets work at any depth.
- Check
pos < len(tokens)before looking attokens[pos], or you will run off the end of the list.