diff --git a/NeetCodeRoadmap/Stack/150_Evaluate_Reverse_Polish_Notation.py b/NeetCodeRoadmap/Stack/150_Evaluate_Reverse_Polish_Notation.py new file mode 100644 index 0000000..226376c --- /dev/null +++ b/NeetCodeRoadmap/Stack/150_Evaluate_Reverse_Polish_Notation.py @@ -0,0 +1,56 @@ +import math +class Solution(object): + def evalRPN(self, tokens): + """ + :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 = [] + + # 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]) + +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(["3","11","+","5","-"])) # 9 +print(obj.evalRPN(["3","-4","+"])) # -1 \ No newline at end of file