From 9f7061263079b3c59f64ce88e19e344191765df2 Mon Sep 17 00:00:00 2001 From: ImAlpha Date: Wed, 27 Sep 2023 07:41:44 -0700 Subject: [PATCH] Solved using recursion --- .../150_Evaluate_Reverse_Polish_Notation.py | 78 ++++++++----------- 1 file changed, 33 insertions(+), 45 deletions(-) diff --git a/NeetCodeRoadmap/Stack/150_Evaluate_Reverse_Polish_Notation.py b/NeetCodeRoadmap/Stack/150_Evaluate_Reverse_Polish_Notation.py index 226376c..b2dd831 100644 --- a/NeetCodeRoadmap/Stack/150_Evaluate_Reverse_Polish_Notation.py +++ b/NeetCodeRoadmap/Stack/150_Evaluate_Reverse_Polish_Notation.py @@ -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 \ No newline at end of file +print(obj.evalRPN(["3","-4","+"])) # -1 +print(obj.evalRPN(["3","11","5","+","-"])) # -13 \ No newline at end of file