56. Evaluate postfix notation
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 // 2is -4: don't use it.)
Example 1
tokens = ["2", "3", "+", "4", "*"]20Example 2
tokens = ["7", "2", "/"]3Example 3
tokens = ["-7", "2", "/"]-3Constraints
tokenshas 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).
- Use a list as a stack:
append()puts a value on top andpop()takes the top one off. A number goes straight on the stack. - An operator pops two values. The first one popped is the right-hand one:
b = stack.pop(), thena = stack.pop(), then pusha - b(notb - a). - Test for the four operators by name; don't use
token.isdigit()to spot numbers, since"-3"has a minus sign. For division,int(a / b)rounds toward zero.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.