标签:split div ret float port tom inner 结果 add
import re def atom_cal(exp): # 计算乘除法 if ‘*‘ in exp: a,b = exp.split(‘*‘) return str(float(a) * float(b)) elif ‘/‘ in exp: a, b = exp.split(‘/‘) return str(float(a) / float(b)) def fuhaochuli(exp): # 符号处理 exp = exp.replace(‘++‘,‘+‘) exp = exp.replace(‘-+‘,‘-‘) exp = exp.replace(‘+-‘,‘-‘) exp = exp.replace(‘--‘,‘+‘) return exp def mul_div(exp): # 匹配乘除法进行计算并替换 while True: ret = re.search(‘\d+(\.\d+)?[*/]-?\d+(\.\d+)?‘,exp) if ret: a = ret.group() b = atom_cal(a) exp = exp.replace(a,b) else:return exp def add_sub(exp): # 匹配加减法计算并进行替换 res = re.findall(‘[-+]?\d+(?:\.\d+)?‘,exp) exp_sum = 0 for i in res: exp_sum += float(i) return exp_sum def cal(exp): # 计算 exp = mul_div(exp) exp = fuhaochuli(exp) exp_sum = add_sub(exp) return exp_sum def main(exp): # 格式处理,计算结果并进行替换 exp = exp.replace(" ",‘‘) while True: ret = re.search(‘\([^()]+\)‘,exp) if ret: inner_bracket = ret.group() res = str(cal(inner_bracket)) exp = exp.replace(inner_bracket,res) exp = fuhaochuli(exp) else:break return cal(exp) s = ‘3*(1+3-0.62)‘ ret = main(s) print(ret)
标签:split div ret float port tom inner 结果 add
原文地址:https://www.cnblogs.com/zbw582922417/p/9526262.html