实现能计算类似 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )等类似公式的计算器程序
# -*- encoding:utf-8 -*- import re def dealwith(exp): exp = exp.replace("+-", '-') exp = exp.replace("--", '+') return exp def cal_exp_son(exp_son): if '/' in exp_son: a, b = exp_son.split('/') return str(float(a)/float(b)) elif '*' in exp_son: a, b = exp_son.split('*') return str(float(a)*float(b)) def cal_express_no_bracker(exp): exp = exp.strip("()") while True: ret = re.search('d+.?d*[*/]-?d+.?d*', exp) if ret: exp_son = ret.group() ret = cal_exp_son(exp_son) exp = exp.replace(exp_son,ret) exp = dealwith(exp) else: ret = re.findall('-?d+.?d*', exp) sum = 0 for i in ret: sum += float(i) return str(sum) def remove_bracket(new_express): """ 提取括号里没有其他括号的表达式 :param new_express: 表达式字符串 :return: 表达式计算的结果 """ while True: ret = re.search('([^()]+)', new_express) # 查找最内层含有括号的 if ret: express_no_bracker = ret.group() ret = cal_express_no_bracker(express_no_bracker) # 计算括号里的结果 exp = new_express.replace(express_no_bracker, ret) new_express = dealwith(exp) else: ret = cal_express_no_bracker(new_express) return ret express = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )' # 去空格 new_express = express.replace(' ', '') result = remove_bracket(new_express) print(result)