classSolution: defevalRPN(self, tokens: List[str]) -> int: iflen(tokens) == 0: return0 # 注意一个数的情况 iflen(tokens) == 1: returnint(tokens[0]) stack = [] ops = ['+', '-', '*', '/'] c = 0 for token in tokens: if token in ops: # print(token, stack) b = stack.pop() a = stack.pop() if token == "+": c = a + b elif token == "-": c = a - b elif token == "*": c = a * b else: c = int(a/b) stack.append(c) else: stack.append(int(token)) return c
classSolution: defcalculate(self, s: str) -> int: defcal(ops, nums): iflen(ops) == 0: return whilelen(ops) > 0and ops[-1] != '('andlen(nums) >= 2: op = ops.pop() b = nums.pop() a = nums.pop() if op == '+': nums.append(a+b) if op == '-': nums.append(a-b) n = len(s) if n == 0: return0 ops = collections.deque() nums = collections.deque() # 若开头为符号,加个0方便计算 if s[0] == '-': nums.append(0) i = 0 while i < n: # print('i', i, '\n') e = s[i] if e == ' ': i += 1 elif e == '(': ops.append(e) i += 1 elif e == '+'or e == '-': # 加入符号前,先做判断,将可以计算的部分先计算结果放入nums栈 cal(ops, nums) ops.append(e) # 如果左括号内第一个数是符号,那先补0,方便计算 if i > 0and s[i-1] == '(': nums.append(0) i += 1 elif e == ')': cal(ops, nums) op = ops.pop() i += 1 else: num = 0 # print("-----", ops, nums) while i < n and'0' <= s[i] and s[i] <= '9': num = 10*num + int(s[i]) i += 1 nums.append(num) # 最后可能存在一个括号外的符号和数字需要计算 cal(ops, nums) returnsum(nums)
def cal(ops, nums): iflen(ops) == 0: return iflen(ops) > 0and ops[-1] != '('andlen(nums) >= 2: op = ops.pop() b = nums.pop() a = nums.pop() if op == '+': nums.append(a+b) if op == '-': nums.append(a-b) if op == '*': nums.append(a*b) if op == '/': nums.append(int(a/b)) n = len(s) if n == 0: return0 ops = [] nums = [] # 若开头为符号,加个0方便计算 if s[0] == '-': nums.append(0) i = 0 while i < n: e = s[i] ife == ' ': i += 1 elif e == '(': ops.append(e) i += 1 elif e in ['+', '-', '*', '/']: # 加入符号前,先做判断,将可以计算的部分先计算结果放入nums栈 while ops and get_priority(e) <= get_priority(ops[-1]): cal(ops, nums) ops.append(e) # 如果左括号内第一个数是符号,那先补0,方便计算 if i > 0and s[i-1] == '(': nums.append(0) i += 1 elif e == ')': while ops and ops[-1] != '(': cal(ops, nums) op = ops.pop() i += 1 else: num = 0 # print("-----", ops, nums) while i < n and'0' <= s[i] and s[i] <= '9': num = 10*num + int(s[i]) i += 1 nums.append(num) # print('i', i, ops, nums) # 最后可能存在一个括号外的符号和数字需要计算 while ops: cal(ops, nums) return sum(nums)