Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/. Each operand may be an integer or another expression.

Note:

  • Division between two integers should truncate toward zero.
  • The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.

Example 1:

Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Example 3:

Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
import string
nums = string.digits
operator = ['+', '-', '*', '/'] for token in tokens:
if token in operator:
last_one = stack.pop()
last_two = stack.pop()
cur_val = self.helper(last_one, last_two, token)
stack.append(cur_val)
else:
stack.append(int(token))
return stack.pop() def helper(self, last_one, last_two, operator):
if operator == '+':
return last_two + last_one
elif operator == '-':
return last_two - last_one
elif operator == '*':
return last_two * last_one
elif operator == '/':
# special case to get ceiling value
if last_two * last_one < 0 and last_two % last_one != 0:
return last_two // last_one + 1
else:
return last_two // last_one
else:
return

最新文章

  1. T-SQL 将存储过程结果插入到表中
  2. 国内其他的maven库
  3. 关于MVC4项目从32位机移到64位机编译报错解决方案
  4. performSelector的原理以及用法
  5. mac 下 终端常用命令
  6. 一个响应式数据库框架SQLBrite,完美解决数据库和UI的同步更新!
  7. Python设计模式——外观模式
  8. 你好,C++(16)用表达式表达我们的设计意图——4.1 用操作符对数据进行运算
  9. Delphi IDHTTP用法详解(六种用法)
  10. springmvc 之 深入核心研究
  11. Junit4学习(六)Junit4参数化设置
  12. 实用的shell脚本面试题和答案
  13. java打印系统时间
  14. 2017-12-15python全栈9期第二天第三节之使用while循环输出1到100的奇数,
  15. MySQL数据库基本命令-1
  16. 【转】scapy 构造以太网注入帧
  17. textInput事件
  18. Python 程序员都会喜欢的 6 个库
  19. C#拖拽操作
  20. php -- PHP在linux上执行外部命令,system(),exec(),shell_exec()

热门文章

  1. 第二季第六天 part2 css动画
  2. java 面向对象概述, 函数解析
  3. 微信支付的Demo
  4. cin cout
  5. Java--Json解析
  6. swoole使用内存
  7. 新年在家学java之基础篇-高级类的特性
  8. MongoDB 索引 .explain(&quot;executionStats&quot;)
  9. Kubernetes系列二: 使用kubeadm安装k8s环境
  10. sqlite如何避免重复建表(获取已经存在的表)