STAQ-P2

The postfix calculator

Practice 2 of 6Stacks and queues9 tests

The problem

Work out the value of a postfix expression (lesson 2). tokens is a list of strings. Each one is a whole number, such as '12' or '-3', or one of the operators '+', '-', '*' and '/'. Return the value as an int.

eval_postfix(['2', '1', '+', '3', '*'])     # (2 + 1) * 3 = 9
eval_postfix(['10', '3', '-'])              # 10 - 3 = 7
eval_postfix(['7', '-2', '/'])              # 7 // -2 = -4

'/' means Python’s //, which rounds down. The expression is always valid, and no division is by zero.

Limits

  • Up to 200,001 tokens.

Builds on STAQ-2 Brackets and expressions.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

9 tests, not run yet
Test results
#TestResultReads · time
1SmallNot run
2Order of a minusNot run
3Order of a divideNot run
4A single numberNot run
5Negative numbersNot run
6Divide rounds downNot run
7The lesson's exampleNot run
8Big numbersNot run
9200,000 tokensNot run