计算器
1.计算器方法一
import re MUL = '\d+(\.\d+)?[*/]-?\d+(\.\d+)?' ADD = '-?\d+(\.\d+)?' def fsdf(exp): exp = exp.replace('--','+') exp = exp.replace('+-', '-') exp = exp.replace('-+', '-') exp = exp.replace('++', '+') return exp def mul_div(exp): lis = re.split('([*/])',exp) # print(len(lis)) if lis[1] == '*': result = float(lis[0]) * float(lis[-1]) else: result = float(lis[0]) / float(lis[-1]) return result def add_sub(exp): m = 0 ret = re.finditer(ADD, exp) for ret1 in ret: result = ret1.group() m += float(result) return m def first_(exp): exp = exp.replace(" ","") cp = re.compile('\([^()]*\)') try: while True: ret = re.search(cp,exp) #m = '5+(6-1*(2-3/4))+(5-6/3)' (2-3/4) (5-6/3) m = ret.group() while '*'in m or '/' in m: ret1= re.search(MUL,m) result = mul_div(ret1.group()) m = re.sub(MUL,str(result),m,1) else: m = fsdf(m) result = add_sub(m) exp = re.sub(cp,str(result), exp, 1) except Exception as e: while '*' in exp or '/' in exp: ret1 = re.search(MUL, exp) result = mul_div(ret1.group()) exp = re.sub(MUL, str(result), exp, 1) else: exp = fsdf(exp) result = add_sub(exp) return result result = first_('5*-5+(6-1*(- 2-3/ -4))+( 5-6 /-3)')# print(result)
2.计算器方法二
import re MUL = '\d+(\.\d+)?[*/]-?\d+(\.\d+)?' ADD = '-?\d+(\.\d+)?' def symbol(exp): exp = exp.replace('--','+') exp = exp.replace('+-','-') exp = exp.replace('-+', '-') exp = exp.replace('++', '+') return exp def mul_div(exp): """ 乘除法 :param exp: :return: """ if '*' in exp: a, b = exp.split('*') result = float(a) * float(b) else: a, b = exp.split('/') result = float(a) / float(b) return result def add_sub(exp): m = 0 ret = re.compile(ADD) while True: exp_add_sub = ret.finditer(exp) for i in exp_add_sub: m += float(i.group()) exp = exp.replace(exp, str(m)) return exp def cal_mul_div(exp): ret = re.compile(MUL) while True: m = ret.search(exp) if m: exp_mul_div = m.group() result = mul_div(exp_mul_div) exp = exp.replace(exp_mul_div,str(result)) else:break return exp def all(exp): result = cal_mul_div(exp) result = symbol(result) result = add_sub(result) return result def run(exp): # m = '5+(6-1*(2-3/4))+(5-6/3)' exp = exp.replace(" ","") ret = re.compile("\([^()]+\)") while True: n = ret.search(exp) if n: m = n.group() result = all(m) exp = exp.replace(m,str(result)) else:break result = all(exp) return result exp = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )' result = run(exp) print(result)