您的位置:首页 > 编程语言 > Lua

Evaluate Reverse Polish Notation Leetcode Python

2015-01-22 01:10 567 查看
Evaluate the value of an arithmetic expression in Reverse Polish Notation.

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

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

We need to use an extra stack to solve this problem.

1.append all the none symbol values to the stack,

the pop two element everytime and then take sum/deduct/multiply/divide 

the code is as follow:

class Solution:
# @param tokens, a list of string
# @return an integer
def evalRPN(self, tokens):
stack=[]
for index in range(len(tokens)):
if tokens[index]!='+' and tokens[index]!='-' and tokens[index]!='*' and tokens[index]!='/':
stack.append(int(tokens[index]))
else:
a=int(stack.pop())
b=int(stack.pop())
if tokens[index]=='+':
stack.append(a+b)
if tokens[index]=='-':
stack.append(b-a)
if tokens[index]=='*':
stack.append(a*b)
if tokens[index]=='/':
if a*b<0:
stack.append(-(-b/a))
else:
stack.append(b/a)
return stack.pop()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python leetcode stack