Leetcode 150. Evaluate Reverse Polish Notation
第一次提交: faster than 26%+ 暴风哭泣
import math
class Solution(object):
def opProcess(self, op, num1 , num2):
if op == 0:
return num1 + num2
if op == 1:
return num2 - num1
if op == 2:
return num1 * num2
if op == 3:
if num2 / num1 < 0:
return int(math.ceil(float(num2)/num1))
else:
return int(num2 // num1)
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
if len(tokens) == 1:
return int(tokens[0])
op = "+-*/"
result = 0
numStack = []
for i in tokens:
if i not in op:
numStack.append(int(i))
else:
print(len(numStack))
result = self.opProcess(op.find(i), numStack.pop(),numStack.pop())
numStack.append(result)
return result
4.9号的时候看了 Discuss 里面的答案:
关于如何处理趋向0可以不用math包里面的函数:
stack = []
for t in tokens:
if t not in ["+", "-", "*", "/"]:
stack.append(int(t))
else:
r, l = stack.pop(), stack.pop()
if t == "+":
stack.append(l+r)
elif t == "-":
stack.append(l-r)
elif t == "*":
stack.append(l*r)
else:
# here take care of the case like "1/-22",
# in Python 2.x, it returns -1, while in
# Leetcode it should return 0
if l*r < 0 and l % r != 0:
stack.append(l/r+1)
else:
stack.append(l/r)
return stack.pop()
然后速度提高了 5%的样子(手动再见
2.一款非常elegant的代码,定义符号的表示的方程真心好酷,要学习一下lambda表达式
class Solution:
# @param {string[]} tokens
# @return {integer}
def __init__(self):
self.operators = {
'+': lambda y, x: x + y,
'-': lambda y, x: x - y,
'*': lambda y, x: x * y,
'/': lambda y, x: int(operator.truediv(x, y))
}
def evalRPN(self, tokens):
if not tokens:
return 0
stack = []
for token in tokens:
if token in self.operators:
stack.append(self.operators[token](stack.pop(), stack.pop()))
else:
stack.append(int(token))
return stack[0]
官方的答案:(趋向0 那边的处理也非常巧妙)
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
operators = set(["+", "-", "*", "/"])
for token in tokens:
if token in operators:
num2 = stack.pop()
num1 = stack.pop()
if token == "+":
stack.append(num1+num2)
elif token == "-":
stack.append(num1-num2)
elif token == "*":
stack.append(num1*num2)
else:
stack.append(abs(num1) // abs(num2) * (-1 if num1 * num2 < 0 else 1))
else:
stack.append(int(token))
return stack[0]