题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
import math ops = {'+':1, '-':1,'*':2,'/':2 } def cal(a, b, op): # 计算两个数的结果 if op == "+": return a + b elif op == "-": return a - b elif op == "*": return a * b elif op == "/": return math.floor(a / b) def handleStack(stack_num, stack_op): # 从栈中拿出数字和运算符进行计算,并将结果压栈 b = stack_num.pop() a = stack_num.pop() cop = stack_op.pop() stack_num.append(cal(a, b, cop)) def comp(op1, op2): # 比较运算符的优先级 if op1 == "(": return False else: return ops[op1] >= ops[op2] while True: try: s = input() num = '' stack_num = [] stack_op = [] i = 0 while i < len(s): # 遇到数字或者负号 while (i < len(s) and (s[i].isdigit() # 0位置的减号,或者左括号之后的减号,是负号 or (s[i] == '-' and (i == 0 or s[i-1] == '(')))): num += s[i] i += 1 # 一直遍历到不是数字的位置 if num != '': stack_num.append(int(num)) num = '' if i == len(s): break if s[i] in ops: # 如果是运算符,需要判断运算符优先级,优先级更高的出栈并计算 while (len(stack_op) > 0 and comp(stack_op[-1], s[i])): handleStack(stack_num, stack_op) stack_op.append(s[i]) elif s[i] == '(': # 如果是左括号,入栈 stack_op.append(s[i]) elif s[i] == ')': # 如果是右括号,一直计算直到左括号出栈 while stack_op[-1] != '(': handleStack(stack_num, stack_op) stack_op.pop() i += 1 while(len(stack_op)): # 如果还有运算符,继续出栈计算 handleStack(stack_num, stack_op) print(stack_num[0]) except: break