计算器写法 | '1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'
作者:互联网
import re # 计算乘除的方法 def parse_exp(exp): if "*" in exp: a,b = exp.split("*") # print(a,b) return str(float(a) * float(b)) if "/" in exp: a,b = exp.split("/") return str(float(a) / float(b)) # 去除++ +- -- -+ bug情况 def exp_format(exp): exp = exp.replace("+-","-") exp = exp.replace("--","+") exp = exp.replace("-+","-") exp = exp.replace("++","+") return exp # 实际计算 def exp_calc(strvar): # 计算乘除 while True: res_obj = re.search("\d+(\.\d+)?[*/][+-]?\d+(\.\d+)?",strvar) if res_obj: res = res_obj.group() # print(res) #"5*-2" res2 = parse_exp(res) # print(res2) strvar = strvar.replace(res,res2) else: break # print(strvar) # 计算加减 res = exp_format(strvar) # print(res) lst = re.findall("[+-]?\d+(?:\.\d+)?",res) # print(lst) count = 0 for i in lst: count += float(i) # print(count) return count # 去除括号 def remove_bracket(strvar): while True: res_obj = re.search("\([^()]+\)",strvar) if res_obj: res_exp = res_obj.group() # print(res_exp) # 计算括号里面的值,exp_calc res = str(exp_calc(res_exp)) # print(res,type(res)) # 把算好的实际数值转换成字符串,替换以前的圆括号 strvar = strvar.replace(res_exp,res) else: # 直接返回替换好的字符串 return strvar # 主函数 def main(strvar): # 先把所有的空格去掉 strvar = strvar.replace(" ","") # 去除括号 res = remove_bracket(strvar) # print(res) # 计算最后结果 return exp_calc(res) # strvar = "- 30 +( 40+5*-2)* 2" a = '1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))' res = main(a) print(res) # 验证结果 res = eval(a) print(res)
标签:2998,return,14,res,replace,99,exp,print,strvar 来源: https://www.cnblogs.com/huangjiangyong/p/10960876.html