50 XP

56. Evaluate postfix notation

Intermediate stacks parsing

In postfix notation (also called reverse Polish notation) an operator comes after the two numbers it works on: 3 4 + means 3 + 4. Brackets are never needed: 2 3 + 4 * means (2 + 3) 4, and `2 3 4 +` means 2 + 3 * 4.

Write a function evaluate(tokens) that takes the expression as a list of strings, its numbers and operators in order, and returns its value as a whole number.

  • The operators are +, -, * and /. Each works on the two values just before it, in order: ["7", "2", "-"] is 7 - 2.
  • A number can be negative, written like "-3".
  • Division keeps only the whole part, rounding toward zero: 7 / 2 is 3 and -7 / 2 is -3. (Python's // rounds down, so -7 // 2 is -4: don't use it.)

Example 1

Inputtokens = ["2", "3", "+", "4", "*"]
Output20
Explanation2 + 3 is 5, then 5 * 4 is 20.

Example 2

Inputtokens = ["7", "2", "/"]
Output3
Explanation7 / 2 is 3.5: keep the whole part, 3.

Example 3

Inputtokens = ["-7", "2", "/"]
Output-3
Explanation-3.5 rounded toward zero is -3.

Constraints

  • tokens has 1 to 50 items and is a valid expression: there are always two values for an operator, and one value is left at the end.
  • Numbers are from -1000 to 1000, no division is by zero, and every value along the way is from -1,000,000 to 1,000,000.

Submit also runs 9 more tests you can't see.

Practises Lists (lesson 9).

Code
def evaluate(tokens):
    """Work out a postfix expression.

    tokens: list of str, numbers and the operators
        + - * /
    Returns: int, the value, division rounding toward 0
    """
    # Write your code here
    pass