码迷,mamicode.com
首页 > 其他好文 > 详细

150. Evaluate Reverse Polish Notation(逆波兰表达式)

时间:2018-02-25 19:06:11      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:reverse   stack   solution   script   some   span   pop   token   pos   

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

 1 class Solution:
 2     def evalRPN(self, tokens):
 3         """
 4         :type tokens: List[str]
 5         :rtype: int
 6         """
 7         stack = []
 8         for i in tokens:
 9             if i not in [+,-,*,/]:
10                 stack.append(i)
11             else:
12                 v2 = int(stack.pop())
13                 v1 = int(stack.pop())
14                 if i==+:
15                     stack.append(v1+v2)
16                 if i==-:
17                     stack.append(v1-v2)
18                 if i==*:
19                     stack.append(v1*v2)
20                 if i==/:
21                     stack.append(v1/v2)
22         return int(stack[0])
23         

 

 

 

150. Evaluate Reverse Polish Notation(逆波兰表达式)

标签:reverse   stack   solution   script   some   span   pop   token   pos   

原文地址:https://www.cnblogs.com/zle1992/p/8469734.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!