A stack is LIFO: push and pop at the top of a Python list, underflow when it is empty, and its uses in matching brackets, infix to postfix and evaluating postfix.
| Push and pop | st = [] st.append(10) st.append(20) print(st.pop()) # 20 print(st) # [10] |
| Precedence | * and / above + and −; an operator of equal precedence on the stack is popped first |
| Infix to postfix | A + B * C → ABC*+; (A + B) * C → AB+C*; A − B + C → AB−C+ |
| Evaluating 5, 3, 2, *, + | push 5, 3, 2; * pops 2 and 3, pushes 6; + pops 6 and 5, pushes 11 |
| Order of operands | the first value popped is the right operand: 8, 2, − gives 8 − 2 = 6 |
| Items left | pushes − pops (an underflow pops nothing) |
Convert A / B + C / D to postfix using a stack. Show the stack and the output after each symbol. (a) What is the postfix expression? (b) What is the largest number of symbols on the stack at one time?
Working: operands go to the output; ( is pushed; ) pops to the matching (; an operator pops those of equal or higher precedence first
Answer: (a) AB/CD/+; (b) 2