# -*- encoding: utf-8 -*- import re def multiply_divide(exp): if '/' in exp: a, b = exp.split('/') return str(float(a)/float(b)) if '*' in exp: a, b = exp.split('*') return str(float(a)*float(b)) def deal_with(expr): expr = expr.replace('++', '+') expr = expr.replace('+-', '-') expr = expr.replace('--', '+') expr = expr.replace('-+', '-') return expr def add(expr): ret = re.findall('-?\d+\.?\d?', expr) sum = 0 for i in ret: sum += float(i) return str(sum) def expr_no_bracket(expr): expr = expr.strip('()') # print(expr) # 计算 while 1: ret = re.search('\d+\.?\d*[*/]-?\d+\.?\d*', expr) if ret: expr_son = ret.group() # print(expr_son) new_expr = multiply_divide(expr_son) expr = expr.replace(expr_son, new_expr) else: expr = add(expr) return expr # break expression = '1 - 2 * ( (60-30 +(6-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )' expression = expression.replace(' ', '') print(expression) while 1: ret = re.search('\([^()]+\)', expression) if ret: expr_brackets = ret.group() print(expr_brackets) new_exp = expr_no_bracket(expr_brackets) expression = expression.replace(expr_brackets, new_exp) expression = deal_with(expression) print(new_exp) print(expression) else: break