LeetCode-Q150-Evaluate Reverse Polish Notation
来源:互联网 发布:linux怎么执行命令 编辑:程序博客网 时间:2024/06/11 16:22
自己思路
无参考
利用栈的数据结构,从头遍历给定序列,把操作数存入栈中,遇到操作符时,将栈中前两个操作数弹出进行计算,结果继续推入栈中,知道最后一次计算完毕,弹出最后结果。代码
class SolutionQ150(object): def evalRPN(self, tokens): stack = [] operations = {"+":lambda x,y: y+x, "-":lambda x,y: y-x, "*": lambda x,y: y*x, "/": lambda x,y: y/x} for i in tokens: if i in operations: stack.append(int(operations[i](stack.pop(),stack.pop()))) else: stack.append(float(i)) return int(stack.pop())
其中将操作符以lambda函数形式存在字典中;代码中有一个细节,在stack.append(float(i))处,可能会问为什么前面的计算结果可以存为int类型,在开始存入操作数的时候要存为float类型呢?原因是Python中对int计算的非整数结果是向下取整的,比如int(13/5)=2,int(-13/5)=-3,而如果不存为float,存为int的话,当出现int(-1/3)时,按照题意应该返回0,但是int的取整方式会存为-1。但是int()在对float类型进行转换时,会将浮点数部分(小数)去掉,即int(-0.1)=0,所以在存操作数时存为float类型即可解决问题。
0 0
- LeetCode-Q150-Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation | leetcode
- leetcode-Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- LeetCode - Evaluate Reverse Polish Notation
- LeetCode | Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation (LeetCode)
- leetcode: Evaluate Reverse Polish Notation
- Leetcode Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation -- LeetCode
- 【LeetCode】Evaluate Reverse Polish Notation
- LeetCode-Evaluate Reverse Polish Notation
- LeetCode:Evaluate Reverse Polish Notation
- LeetCode Evaluate Reverse Polish Notation
- Nginx+Center OS 7.2 开机启动设置(转载)
- [P2731]骑马修栅栏
- XML DTD详解
- FFT 【JSOI2012】bzoj4332 分零食
- Java数据类型总结:基本类型、引用类型
- LeetCode-Q150-Evaluate Reverse Polish Notation
- Appium下载遇到的问题
- 正则表达式
- 51nod 1441 士兵的数字游戏【素数筛】
- 设计模式 外观模式 一键电影模式
- CSS3新增常用属性
- pat-top 1012. Greedy Snake (35)
- CRC校验算法
- angularjs官方教程 -- 环境部署