Evaluating expressions: postfix
A postfix expression puts each operator after its two operands, so 3 + 4 * 2 becomes 3 4 2 * +; it needs no brackets or precedence, and one stack evaluates it in a single left-to-right pass, O(n).
People write 3 + 4 * 2 and rely on "multiply before adding" and brackets. A program reads from left to right, and at the + it cannot know whether a * is coming, so it has to wait. The fix is another way of writing it: postfix (also called Reverse Polish notation), with each operator after its two numbers: 3 4 2 * +. It needs no brackets and no precedence; one stack and one pass from left to right work it out, each token going on and off the stack once, O(n). CPython does this itself: it compiles a + b * c into instructions like LOAD a, LOAD b, LOAD c, *, + and runs them on a stack, which is exactly postfix.
Tokens first
Before working anything out, cut the string into tokens: numbers, operators, brackets. If the tokens are separated by spaces, split() is all it takes; it splits on runs of whitespace, so extra spaces do no harm.
1expr = "12 3 4 * +"2tokens = expr.split()3print(tokens)4print(len(tokens), tokens[0], int(tokens[0]) + 1)5print(" 9 3 - ".split())
['12', '3', '4', '*', '+'] 5 12 13 ['9', '3', '-']
Note that tokens[0] is the string '12'; it takes int() to make it a number. People often write expressions without spaces, like 12+3*(40-5); then read one character at a time, collecting digits, and put the number in when a character that is not a digit comes along.
1def tokenize(s):2 tokens = []3 num = ""4 for ch in s:5 if ch.isdigit():6 num += ch # a number may be several digits: collect them7 else:8 if num:9 tokens.append(num)10 num = ""11 if ch in "+-*/()":12 tokens.append(ch) # spaces do nothing13 if num:14 tokens.append(num)15 return tokens16 17print(tokenize("12+3*(40-5)"))18print(tokenize(" 7 * 6 "))
['12', '+', '3', '*', '(', '40', '-', '5', ')']
['7', '*', '6']
An expression without spaces is split into tokens. What does this print?
1def tokenize(s):2 tokens = []3 num = ""4 for ch in s:5 if ch.isdigit():6 num += ch7 else:8 if num:9 tokens.append(num)10 num = ""11 if ch in "+-*/()":12 tokens.append(ch)13 if num:14 tokens.append(num)15 return tokens16 17print(tokenize("40-5*12"))
num, and the number only goes in when a non-digit arrives, so 40 and 12 are one token each and are not split into single digits. Each operator is a token of its own. The final 12 goes in through the if num: after the loop.Evaluating postfix with a stack
Read from left to right:
- A number: push it.
- An operator: pop twice. The first one out is the right-hand number b, the second is the left-hand number a; work out
a op band push the result. - At the end: exactly one number should be left, and it is the result.
9362121def apply(op, a, b):2 if op == '+':3 return a + b4 if op == '-':5 return a - b6 if op == '*':7 return a * b8 return a // b # whole numbers only in this lesson9 10def eval_postfix(expr):11 stack = []12 for tok in expr.split():13 if tok in ('+', '-', '*', '/'):14 b = stack.pop() # the first one out is the right-hand number15 a = stack.pop()16 stack.append(apply(tok, a, b))17 else:18 stack.append(int(tok))19 if len(stack) != 1:20 raise ValueError("not a complete postfix expression")21 return stack[0]22 23print(eval_postfix("9 3 - 2 *"))24print(eval_postfix("12 3 4 * +"))25print(eval_postfix("5 1 2 + 4 * + 3 -"))26try:27 eval_postfix("1 2 3 +")28except ValueError as e:29 print("error:", e)
12 24 14 error: not a complete postfix expression
The last one ends with two numbers, 1 and 5, on the stack: an operator is missing. The other way round, with an operator too many, stack.pop() raises IndexError on an empty stack.
What does 20 4 / 2 - come to?
1def eval_postfix(expr):2 stack = []3 for tok in expr.split():4 if tok in ('+', '-', '*', '/'):5 b = stack.pop()6 a = stack.pop()7 if tok == '+':8 stack.append(a + b)9 elif tok == '-':10 stack.append(a - b)11 elif tok == '*':12 stack.append(a * b)13 else:14 stack.append(a // b)15 else:16 stack.append(int(tok))17 return stack[0]18 19print(eval_postfix("20 4 / 2 -"))
What is the value of the postfix expression 6 2 3 + *?
+, 3 and 2 are popped and 5 is pushed, leaving 6 5; at *, 6 × 5 = 30. In infix it is 6 * (2 + 3). 15 comes from reading it as 6 × 2 + 3.Reading - means doing three things. Put these three lines in order so that the postfix expression 8 2 - comes out as 6.
a = stack.pop()b = stack.pop()stack.append(a - b)
6
a - b = 6. Swap the first two lines and a and b change places: 2 − 8 = −6.Evaluate postfix
✓Fill in eval_postfix: a number is pushed; an operator pops twice (the first out is the right-hand number) and pushes the result. All four operations, with // for division.
14 16 30
1def eval_postfix(expr):2 stack = []3 for tok in expr.split():4 pass # a number: push int(tok); an operator: b = pop, a = pop, push a op b5 return stack[0] if stack else None6 7print(eval_postfix("2 3 4 * +"), eval_postfix("100 5 / 4 -"), eval_postfix("7 1 - 2 3 + *"))
From infix to postfix
What people write is infix (operators in the middle). Converting it also uses a stack, this time of operators, with precedence in a dict: prec = {'+': 1, '-': 1, '*': 2, '/': 2}.
- A number: straight to the output.
(: push.): pop to the output until a(comes up; drop the(, it never goes to the output.- An operator: first pop every operator on top whose precedence is greater than or equal to its own to the output (stopping at a
(), then push it. - At the end: pop everything left to the output.
| Read | What happens | Operator stack | Output |
|---|---|---|---|
| 2 | a number: to the output | (empty) | 2 |
| * | the stack is empty: push | * | 2 |
| ( | an opening bracket: push | * ( | 2 |
| 3 | to the output | * ( | 2 3 |
| + | the top is (: stop, push | * ( + | 2 3 |
| 4 | to the output | * ( + | 2 3 4 |
| ) | pop down to (: + goes out, ( is dropped | * | 2 3 4 + |
| - | the top * is higher than -: pop; then push - | - | 2 3 4 + * |
| 5 | to the output | - | 2 3 4 + * 5 |
| end | pop everything left | (empty) | 2 3 4 + * 5 - |
1def tokenize(s):2 tokens, num = [], ""3 for ch in s:4 if ch.isdigit():5 num += ch6 else:7 if num:8 tokens.append(num)9 num = ""10 if ch in "+-*/()":11 tokens.append(ch)12 if num:13 tokens.append(num)14 return tokens15 16def to_postfix(tokens):17 prec = {'+': 1, '-': 1, '*': 2, '/': 2}18 out = []19 ops = [] # the operator stack20 for tok in tokens:21 if tok == '(':22 ops.append(tok)23 elif tok == ')':24 while ops[-1] != '(':25 out.append(ops.pop())26 ops.pop() # drop the (27 elif tok in prec:28 while ops and ops[-1] != '(' and prec[ops[-1]] >= prec[tok]:29 out.append(ops.pop())30 ops.append(tok)31 else:32 out.append(tok)33 while ops:34 out.append(ops.pop())35 return out36 37for s in ["2*(3+4)-5", "3+4*2", "8-3+1", "(1+2)*(3+4)"]:38 print(s, "->", " ".join(to_postfix(tokenize(s))))
2*(3+4)-5 -> 2 3 4 + * 5 - 3+4*2 -> 3 4 2 * + 8-3+1 -> 8 3 - 1 + (1+2)*(3+4) -> 1 2 + 3 4 + *
The equal in "greater than or equal" matters: when + comes in, the - on the stack is just as high and has to be popped first, so operators of the same level are worked out from left to right. What if it were only "greater than"? Run it:
1def to_postfix(tokens, pop_equal):2 prec = {'+': 1, '-': 1, '*': 2, '/': 2}3 out, ops = [], []4 for tok in tokens:5 if tok in prec:6 while ops and (prec[ops[-1]] > prec[tok] or (pop_equal and prec[ops[-1]] == prec[tok])):7 out.append(ops.pop())8 ops.append(tok)9 else:10 out.append(tok)11 while ops:12 out.append(ops.pop())13 return out14 15def eval_postfix(tokens):16 stack = []17 for tok in tokens:18 if tok in ('+', '-'):19 b, a = stack.pop(), stack.pop()20 stack.append(a + b if tok == '+' else a - b)21 else:22 stack.append(int(tok))23 return stack[0]24 25tokens = "8 - 3 + 1".split()26for pop_equal in [True, False]:27 post = to_postfix(tokens, pop_equal)28 print(" ".join(post), "=", eval_postfix(post))
8 3 - 1 + = 6 8 3 1 + - = 4
With only "greater than", 8 - 3 + 1 becomes 8 3 1 + -, which is 8 − (3 + 1) = 4: wrong. (** is the exception: 2 ** 3 ** 2 goes from right to left, so a ** does not pop another **.)
What is the infix (3 + 4) * 2 in postfix?
( is pushed; 3 goes out; + is pushed; 4 goes out; ) pops + to the output and drops (; * is pushed; 2 goes out; at the end * is popped. The brackets come first, so 3 4 + is written first.Pick a comparison for the blank so that 8 - 3 + 1 * 2 comes out as the correct postfix 8 3 - 1 2 * +.
1def to_postfix(tokens):2 prec = {'+': 1, '-': 1, '*': 2, '/': 2}3 out, ops = [], []4 for tok in tokens:5 if tok in prec:6 while ops and prec[ops[-1]] prec[tok]:7 out.append(ops.pop())8 ops.append(tok)9 else:10 out.append(tok)11 while ops:12 out.append(ops.pop())13 return out14 15print(" ".join(to_postfix("8 - 3 + 1 * 2".split())))
- of the same level goes first, which keeps the order left to right. * is higher than +, so at * the + stays on the stack and waits, and 1 2 * is written first.In interviews: "Evaluate Reverse Polish notation" and "basic calculator" are common. Say two things clearly and you are halfway there: in subtraction and division the number popped first is the right-hand one; operators of the same level pop first (greater or equal), and a bracket on the stack shields the operators under it.
Infix to postfix
✓Fill in the operator branch and the closing-bracket branch. The tokens are already separated by spaces.
1 2 3 * + 4 - 1 2 + 3 4 - * 5 /
1def to_postfix(expr):2 prec = {'+': 1, '-': 1, '*': 2, '/': 2}3 out, ops = [], []4 for tok in expr.split():5 if tok == '(':6 ops.append(tok)7 elif tok == ')':8 pass # pop to the output until the top is (; then drop the (9 elif tok in prec:10 ops.append(tok) # first pop those on top with precedence >= its own11 else:12 out.append(tok)13 while ops:14 out.append(ops.pop())15 return " ".join(out)16 17print(to_postfix("1 + 2 * 3 - 4"))18print(to_postfix("( 1 + 2 ) * ( 3 - 4 ) / 5"))
Converting by hand in exams: the bracket trick
Exam questions often just want the answer, not every step on the stack. There's a quick way, in three steps:
- Put brackets round every step, in the order it is worked out:
3 + 4 * 2 - 1becomes((3 + (4 * 2)) - 1). - Move each operator just past its closing bracket.
- Drop all the brackets:
3 4 2 * + 1 -.
Move each operator just before its opening bracket instead and you get the prefix expression (Polish notation): - + 3 * 4 2 1. The numbers never change order, only the operators move, which is a quick way to rule out wrong answers.
Which is the postfix form of a * b + c / d?
((a * b) + (c / d)). Each operator goes past its closing bracket: a b *, c d /, and + last, so a b * c d / +. The letters stay in the order a b c d.Which is the prefix form of a + b * (c - d)?
(a + (b * (c - d))). Each operator moves in front of its opening bracket: + a * b - c d. a b c d - * + is the postfix form.How you write it at work
Python has eval("2*(3+4)-5") ready-made, but never hand user input to eval: it runs any code at all, and eval("__import__('os').system(...)") can delete files. When users type expressions (a calculator, spreadsheet formulas, expressions in a config file), the standard way is this lesson's three steps: tokenize, convert to postfix (or convert and evaluate at once with two stacks), evaluate with a stack, knowing only the operators you allow.
- Tokenize with
split(); for expressions without spaces, collect digits one character at a time, as in the tokens stage. - Keep operators and functions in dicts:
prec = {'+': 1, ...},ops = {'+': lambda a, b: a + b, ...}; a new operator is one more line. - Whole-number division is
//,/for fractions; Python's//rounds down, so-7 // 2is-4, unlike C.
1ops = {2 '+': lambda a, b: a + b,3 '-': lambda a, b: a - b,4 '*': lambda a, b: a * b,5 '/': lambda a, b: a / b,6}7 8def eval_postfix(expr):9 stack = []10 for tok in expr.split():11 if tok in ops:12 b = stack.pop()13 a = stack.pop()14 stack.append(ops[tok](a, b))15 else:16 stack.append(float(tok))17 return stack[0]18 19print(eval_postfix("7 2 /"), eval_postfix("1.5 2 * 0.5 -"))
3.5 2.5
What is -7 // 2 in Python?
// rounds down: -3.5 goes towards the smaller number, -4. Integer division in C and Java rounds towards 0 and gives -3. When you write your own calculator, decide which one you want; for decimals use /, which gives -3.5.Summary
Evaluating expressions: postfix first, then a stack
- Tokens: split() when there are spaces, otherwise collect digits one character at a time
- Postfix: a number is pushed; an operator pops b, then a, and pushes a op b
- Infix to postfix: an operator stack; pop those greater or equal, then push; ( shields, ) pops down to (
- Never hand a user's expression to eval
1for tok in expr.split():2 if tok in ops:3 b = stack.pop(); a = stack.pop()4 stack.append(ops[tok](a, b))5 else:6 stack.append(int(tok))