总结一下今天在codewars上做的一道关于求解逆波兰表达式(Revese Polish Notation Calculator)的题目。
题目内容如下:
Your job is to create a calculator which evaluates expressions inReverse Polish notation.
For example expression 5 1 2 + 4 * + 3 - (which is equivalent to 5 + ((1 + 2) * 4) - 3 in normal notation) should evaluate to 14.
Note that for simplicity you may assume that there are always spaces between numbers and operations, e.g. 1 3 + expression is valid, but 1 3+ isn't.
Empty expression should evaluate to 0.
Valid operations are +, -, *, /.
You may assume that there won't be exceptional situations (like stack underflow or division by zero).
比如说给你一个字符串"1 3 -",你要返回结果-2。
逆波兰表达式的计算,常用的方法是通过堆栈进行处理。
下面是我的代码:
def calc(expr):
token=[]
for i in expr.split():
if i in ['+','-','*','/']:
first, second=token.pop(), token.pop()
token.append(str(eval(second+i+first)))
else:
token.append(i)
return eval(token.pop()) if token else 0
从代码的安全性考虑,这里其实还有几个地方有待商榷。主要是eval()这个函数的使用,可能会引起安全问题。具体解决方法可以import operator,使用operator.add等方法取代上述的eval(y+i+x)的表达