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
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
9 tests, not run yet
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | Small | Not run | |
| 2 | Order of a minus | Not run | |
| 3 | Order of a divide | Not run | |
| 4 | A single number | Not run | |
| 5 | Negative numbers | Not run | |
| 6 | Divide rounds down | Not run | |
| 7 | The lesson's example | Not run | |
| 8 | Big numbers | Not run | |
| 9 | 200,000 tokens | Not run |