Thursday, September 11, 2014

Leetcode (Python): Evaluate Reverse Polish Notation



Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +-*/. Each operand may be an integer or another expression.
Some examples:
  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

Solution:

class Solution:
    # @param tokens, a list of string
    # @return an integer
    def evalRPN(self, tokens):
        if tokens == None:
            return 0
        stack = []
        for token in tokens:
            if token =="+" or token =="-" or token =="*" or token =="/":
                operand2 = stack.pop()
                operand1 = stack.pop()
                if token == "+":
                    stack.append(operand1+operand2)
                elif token == "-":
                    stack.append(operand1-operand2)
                elif token == "*":
                    stack.append(operand1*operand2)
                else:
                    stack.append(int(float(operand1)/operand2))
            else:
                stack.append(int(token))
        return stack.pop()

No comments :

Post a Comment