Solved using recursion
This commit is contained in:
parent
b285140f84
commit
9f70612630
@ -5,52 +5,40 @@ class Solution(object):
|
||||
:type tokens: List[str]
|
||||
:rtype: int
|
||||
"""
|
||||
valid_tokens = {
|
||||
'+': lambda x, y: x + y,
|
||||
'-': lambda x, y: x - y,
|
||||
'*': lambda x, y: x * y,
|
||||
'/': lambda x, y: x / y,
|
||||
}
|
||||
tmp = []
|
||||
# operators = {
|
||||
# '+': lambda x, y: x + y,
|
||||
# '-': lambda x, y: x - y,
|
||||
# '*': lambda x, y: x * y,
|
||||
# '/': lambda x, y: x / y,
|
||||
# }
|
||||
# stack = [] # Space: O(n)
|
||||
# for token in tokens: # Time: O(n)
|
||||
# if token not in operators:
|
||||
# stack.append(int(token))
|
||||
# else:
|
||||
# x = stack.pop(-2)
|
||||
# y = stack.pop()
|
||||
# stack.append(math.ceil(operators[token](x, y)))
|
||||
# return int(stack[-1])
|
||||
|
||||
# while len(tokens) != 1:
|
||||
blanks = 0
|
||||
count = 0
|
||||
for x in range(len(tokens)):
|
||||
# print(tokens[x])
|
||||
if tokens[x] in valid_tokens:
|
||||
operator = valid_tokens[tokens[x]]
|
||||
if len(tmp) > 1 and count == 0:
|
||||
a = tmp.pop()
|
||||
b = tmp.pop()
|
||||
tokens.append(math.floor(operator(b, a)))
|
||||
# print(tmp)
|
||||
# print(tokens)
|
||||
tokens[x] = None
|
||||
count += 1
|
||||
else:
|
||||
a = tmp.pop()
|
||||
b = tokens.pop()
|
||||
tokens.append(math.ceil(operator(a, b)))
|
||||
tokens[x] = None
|
||||
else:
|
||||
tmp.append(int(tokens[x]))
|
||||
tokens[x] = None
|
||||
# print(tokens)
|
||||
# print(tmp)
|
||||
for y in tokens:
|
||||
if y is None:
|
||||
blanks += 1
|
||||
# print(blanks)
|
||||
tokens = tokens[blanks:]
|
||||
if tokens[0] < 0:
|
||||
tokens[0] *= -1
|
||||
return int(tokens[0])
|
||||
# Recursion Solution
|
||||
s = tokens[len(tokens) - 1]
|
||||
tokens.pop()
|
||||
print(tokens)
|
||||
if(s not in '+-/*'): return int(s)
|
||||
else:
|
||||
a = self.evalRPN(tokens)
|
||||
b = self.evalRPN(tokens)
|
||||
if(s == "+"): return a + b
|
||||
elif(s == "*"): return a * b
|
||||
elif(s == "-"): return b - a
|
||||
else: return int(float(b)/a)
|
||||
|
||||
obj = Solution()
|
||||
# print(obj.evalRPN(["2","1","+","3","*"])) # 9
|
||||
# print(obj.evalRPN(["4","13","5","/","+"])) # 6
|
||||
# print(obj.evalRPN(["10","6","9","3","+","-11","*","/","*","17","+","5","+"])) # 22
|
||||
# print(obj.evalRPN(["0","3","/"])) # 0
|
||||
print(obj.evalRPN(["2","1","+","3","*"])) # 9
|
||||
print(obj.evalRPN(["4","13","5","/","+"])) # 6
|
||||
print(obj.evalRPN(["10","6","9","3","+","-11","*","/","*","17","+","5","+"])) # 22
|
||||
print(obj.evalRPN(["0","3","/"])) # 0
|
||||
print(obj.evalRPN(["3","11","+","5","-"])) # 9
|
||||
print(obj.evalRPN(["3","-4","+"])) # -1
|
||||
print(obj.evalRPN(["3","11","5","+","-"])) # -13
|
||||
Loading…
Reference in New Issue
Block a user