Expert · Parsing · 254 of 264
Expression calculator
Evaluate an expression with whole numbers, + - * and brackets, following the usual order (* before + and -). Write the parser yourself (no eval).
Input: an expression, possibly with spaces. Output: its value.
Examples
Input
2 + 3 * 4
Output
14
Input
(2 + 3) * 4
Output
20
Input
7
Output
7
2 more tests check other inputs when you press Check.
Stuck? The idea behind parsing
Turning text into structure: read it piece by piece (tokens: numbers, operators, brackets), then work out what they mean, in order.
A stack keeps what is waiting, such as an operator until both its numbers are known.
tokens = "3 4 + 2 *".split()
stack = []
for t in tokens:
if t in "+*":
b, a = stack.pop(), stack.pop()
stack.append(a + b if t == "+" else a * b)
else:
stack.append(int(t))
print(stack[0]) # 14Watch for: Never run the text with eval(): work it out yourself, so you decide what is allowed.