Data structures · 7 / 15 Exercise Medium

Postfix calculator

Objective

Create a Python program that evaluates expressions in postfix notation (RPN), where operators come after the operands. They are solved very neatly with a stack.

Instructions

  • Read an integer n and then n expressions, one per line, with the items separated by spaces. Operands are integers and operators are +, -, * and / (integer division, like //).
  • Go through the items: a number is pushed; an operator pops the last two numbers (the first one popped is the right operand), computes and pushes the result.
  • Show the result of each expression. If there is a division by zero, show Error: division by zero.
Input
3
3 4 +
5 1 2 + 4 * + 3 -
8 0 /
Output
7
14
Error: division by zero

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

Start exercise