Practice

Problem 7 of 10

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 / 2 gives 3, and -7 / 2 gives -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

  1. Task 1, not checked yet. Make calculate_rpn pass the example tests.

  2. Task 2, not checked yet. Make calculate_rpn pass the hidden tests.

Task 1 of 2

Make calculate_rpn pass the example tests.

All tasks

main.py

Ctrl+Enter runs your code. Ctrl+Shift+Enter runs all the tests. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.