题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
def cal(a, o, b): a, b = str(a), str(b) u = a + o + b return eval(u) s_ = input() n = len(s_) all_list = [] num_list = [] op_list = [] search_digit = True i = 0 while i < n: if s_[i] in "()[]}{": all_list.append(s_[i]) i += 1 continue if not search_digit: all_list.append(s_[i]) i += 1 search_digit = True continue num = "" if s_[i] == "-": num += "-" i += 1 while i < n and s_[i].isdigit(): num += s_[i] i += 1 all_list.append(int(num)) search_digit = False for item in all_list: if type(item) == int: num_list.append(item) continue if item in "([{": op_list.append(item) continue if item in ")]}": while op_list[-1] not in "([{": op = op_list.pop() n2 = num_list.pop() n1 = num_list.pop() num_list.append(cal(n1, op, n2)) op_list.pop() continue if item in "-+": if len(op_list) == 0 or op_list[-1] in "([{": op_list.append(item) continue while len(op_list) != 0 and op_list[-1] not in "([{": op = op_list.pop() n2 = num_list.pop() n1 = num_list.pop() num_list.append(cal(n1, op, n2)) op_list.append(item) continue if item in "*/": if len(op_list) == 0 or op_list[-1] in "([{-+": op_list.append(item) continue while len(op_list) != 0 and op_list[-1] not in "([{-+": op = op_list.pop() n2 = num_list.pop() n1 = num_list.pop() num_list.append(cal(n1, op, n2)) op_list.append(item) continue while len(op_list) != 0: op = op_list.pop() n2 = num_list.pop() n1 = num_list.pop() num_list.append(cal(n1, op, n2)) print(int(num_list[0]))