Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
operator = ['+', '-', '*', '/']
while len(tokens) != 1:
a = 0
b = 0
for i in range(len(tokens)-2):
if tokens[i+2] in operator:
a = int(tokens[i])
b = int(tokens[i+1])
print(i, a, b)
if tokens[i+2] == operator[0]:
tokens[i+2] = str(a+b)
elif tokens[i+2] == operator[1]:
tokens[i+2] = str(a-b)
elif tokens[i+2] == operator[2]:
tokens[i+2] = str(a*b)
elif tokens[i+2] == operator[3]:
tokens[i+2] = str(int(a/b))
print(tokens[i+2])
tokens.pop(i+1)
tokens.pop(i)
print(tokens)
break
return tokens[0]
첨엔 tokens[i]
, tokens[i+1]
, tokens[i+2]
세개씩 세트로 보고
tokens[i+2]
가 연산자면 계산값을 넣고 i 와 i+1 은 지워주는 방식으로 했는데.. Output Limit Exceeded
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
operator = ['+', '-', '*', '/']
stack = []
for e in tokens:
if e in operator:
b = int(stack.pop())
a = int(stack.pop())
if e == operator[0]:
stack.append(a + b)
elif e == operator[1]:
stack.append(a - b)
elif e == operator[2]:
stack.append(a * b)
else:
tmp = int(a/b)
stack.append(tmp)
else:
stack.append(e)
return stack.pop()
stack 을 이용하면 된다..!!