Stacks and queues · Problem 3 of 3

Evaluate a calculator in postfix notation

Pattern: Evaluate Reverse Polish Notation

mediumNot solved yet

The problem

Some calculators take expressions in postfix order (also called reverse Polish notation): the operator comes after its two numbers. 3 4 + means 3 + 4, and 5 1 2 + 4 * + 3 - means 5 + (1 + 2) * 4 - 3.

Write a function that takes the expression as a list of tokens and returns its value. Tokens are whole numbers (possibly negative, like "-7") or one of +, -, *, /. Division keeps only the whole-number part, rounding toward zero: 7 / 2 is 3 and -7 / 2 is -3. The input is always a valid expression with no division by zero.

text
1evaluate_postfix(["3", "4", "+"])                    ->  7
2evaluate_postfix(["5", "1", "2", "+", "4", "*", "+", "3", "-"])  ->  14
3evaluate_postfix(["-7", "2", "/"])                   ->  -3
Evaluating example 21 / 9
token
5
1
2
+
4
*
+
3
-
5top →

Push 5.

Write evaluate_postfix(tokens) in Python or evaluatePostfix(tokens) in JavaScript.

Runs privately in your browser. Nothing is sent to a server.Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Write your function, then run it against 22 tests.

Breakdown

Stuck? Reveal one step at a time, and try again after each one.

  1. Step 2
  2. Step 3
  3. Step 4

Solution

?

Give it a real try first: you learn far more from a wrong attempt than from reading the answer.