Problem · Medium · 25 min
Reverse Polish calculator
- Medium
- Stacks
- Parsing text
In reverse Polish notation, an operator comes after its two numbers. 3 4 + means 3 + 4. 2 3 4 * + means 2 + (3 * 4).
Write calculate_rpn(tokens). It takes a list of strings. Each string is a whole number such as "12" or "-3", or one of the operators "+", "-", "*" and "/". It returns the result as an integer.
- Read the tokens from left to right. A number goes on a stack. An operator takes the top two numbers from the stack and puts the result back. The second number from the top is the left side:
["5", "2", "-"]means 5 - 2. - Division gives a whole number. It cuts off the decimals toward zero:
7 / 2gives 3, and-7 / 2gives -3. - The input is valid. A divisor is never 0. At the end, the stack has exactly one number.
Examples
| Call | Result |
|---|---|
calculate_rpn(['3', '4', '+']) |
7 |
calculate_rpn(['2', '3', '4', '*', '+']) |
14 |
calculate_rpn(['7', '2', '/']) |
3 |
Tasks
2 to do
Task 1, not checked yet. Make
calculate_rpnpass the example tests.Task 2, not checked yet. Make
calculate_rpnpass the hidden tests.
Task 1 of 2
Make calculate_rpn pass the example tests.