您的位置:首页 > 编程语言 > Python开发

LintCode:逆波兰表达式求值

2016-07-25 00:00 483 查看
LintCode:逆波兰表达式求值

被Python里的正负数相除坑了,在Python中,正数除负数是向下取整的,如
6/(-132)=-1
而在C/C++中是向零取整的,结果是0。

class Solution:
# @param {string[]} tokens The Reverse Polish Notation
# @return {int} the value
def evalRPN(self, tokens):
# Write your code here
L = []
for elem in tokens:
try:
(int(elem))
L.append(int(elem))
except:
a = L.pop()
b = L.pop()
c = eval(str(b) + elem + str(a))
#python中,正数除负数是向下取整,而C/C++是向零取整
#如在Python中 6/(-132) = -1,而在C/C++中结果是0
#因而对这种情况需要特殊处理
if elem == '/':
if c < 0:
if b % a != 0:
c += 1
L.append(c)
return L[0]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python