leetcode-150- reverse Polish expression evaluation

 Subject description:

method one:

class Solution:
    def evalRPN(self, t: List[str]) -> int:
        d=[] 
        n=len(t) 
        for i in range(n): 
            if '0'<=t[i][-1]<='9': 
                d+=[t[i]] 
            else: 
                d[-2]=str(int(eval((d[-2]+t[i]+d[-1])))) 
                d.pop() 
        return int(d[0])

 Method Two:

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        symbol = ['+', '-', '*', '/'] 
        stack = [] 
        for t in tokens: 
            if t in symbol: 
                stack.append(self.eval(stack.pop(-2), stack.pop(), t)) 
            else: 
                stack.append(int(t)) 
        return stack[-1] 
    def eval(self, x, y, symbol): 
        if symbol == '+': return x + y 
        if symbol == '-': return x - y 
        if symbol == '*': return x * y 
        if symbol == '/': return int(x / y)

 

Guess you like

Origin www.cnblogs.com/oldby/p/11202744.html