题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
def compute(s): #数字 temp_num = "" #运算符 comp = [] i=0 l = len(s) while i< l: if s[i] in ['+','-','*','/']: comp.append(s[i]) temp_num +=" " elif s[i] in ['(','[','{']: find_open = dict(zip(['(','[','{'],[')',']','}'])) flag = 1 j = i+1 while j < len(s) : if s[j] == s[i]: flag +=1 elif s[j] == find_open[s[i]]: flag -=1 if flag == 0: break j += 1 temp_num += str(compute(s[i+1:j])) i = j else: temp_num +=s[i] i+=1 num =[eval(i) for i in temp_num.split()] if len(num) == len(comp): #有符号位 num[0] = -num[0] if s[0] == '-' else num[0] comp = comp[1:] #入栈运算 que = [num[0]] for i in range(len(comp)): if comp[i] == '+': que.append(num[i+1]) elif comp[i] == '-': que.append(-num[i+1]) elif comp[i] == '*': temp = que.pop() que.append(temp*num[i+1]) elif comp[i] == '/': temp = que.pop() que.append(temp/num[i+1]) return sum(que) s = input() out = compute(s) print(int(out))