标签:
1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))
求上述表达式的结果
分析:对于上述表达式,涉及的括号及运算符较多,需使用正则表达式来匹配相应的字符,将字符进行分开计算
1、提取最里层括号里面的内容
2、计算最里层括号内的乘除运算,并将结果替换到原表达式
3、循环执行前两步的结果
1 import re 2 # formula = "1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))" 3 # #含义:匹配括号,但是不匹配成对的括号,按正则表达式进行分割,最大分割次数为1次,取出最内层的括号内的一组元素 4 # val = re.split(‘\(([^()]+)\)‘,formula,1) 5 # before,center,last=val 6 # print(val) 7 # #将取出的内容进行运算 8 # if "*" in center: 9 # new_center=re.split("\*",center) 10 # sub_res=float(new_center[0])*float(new_center[1]) 11 # print("单步计算结果为:",sub_res) 12 # 13 # elif "/" in center: 14 # new_center=re.split("/",center) 15 # sub_res=float(new_center[0])/float(new_center[1]) 16 # print("单步计算结果为:",sub_res) 17 # 18 # formula=before+str(sub_res)+last 19 # print(formula) 20 # val1 = re.split(‘\(([^()]+)\)‘,formula,1) 21 # print(val1) 22 # val2= re.split(‘(\d+\.?\d*[*/][\-]?\d+\.?\d*)‘,formula,1) 23 # print("val2:",val2) 24 # before1,center1,last1=val2 25 # 26 # if "*" in center1: 27 # new_center=re.split("\*",center1) 28 # print("111:",new_center) 29 # sub_res=float(new_center[0])*float(new_center[1]) 30 # print("单步计算结果为:",sub_res) 31 # 32 # elif "/" in center1: 33 # new_center=re.split("/",center1) 34 # sub_res=float(new_center[0])/float(new_center[1]) 35 # print("单步计算结果为:",sub_res) 36 37 38 39 40 41 #计算,首先利用正则表达式,匹配最内层括号,并取出最内层括号内的元素,然后进行最内层括号内运算 42 def calc(formula): 43 while True: 44 #取最里层括号里面的内容,进行运算 45 val =re.split(‘\(([^()]+)\)‘,formula,1) 46 if len(val)==3: 47 before,center,last=val 48 new_center=mul_div(center) 49 formula=before+str(new_center)+last 50 else: 51 return mul_div(formula) 52 53 def mul_div(formula): 54 while True: 55 #取优先级高的,进行拆分计算 56 val1=re.split(‘(\d+\.?\d*[*/][\-]?\d+\.?\d*)‘,formula,1) 57 if len(val1)==3: 58 bef,cent,la=val1 59 if "*" in cent: 60 new_cent=re.split("\*",cent) 61 sub_res=float(new_cent[0])*float(new_cent[1]) 62 formula=bef+str(sub_res)+la 63 elif "/" in cent: 64 new_cent=re.split("/",cent) 65 sub_res=float(new_cent[0])*float(new_cent[1]) 66 formula=bef+str(sub_res)+la 67 else: 68 return final(formula) 69 70 def final(formula): 71 #由前面的分析结果可以看出,拆分时运算符被拆分,但计算结果有时含有运算符,故需进行替换 72 formula = formula.replace(‘++‘,‘+‘).replace(‘+-‘,‘-‘).replace(‘-+‘,‘-‘).replace(‘--‘,‘+‘) 73 num = re.findall(‘[+\-]?\d+\.?\d*‘,formula) 74 total = 0 75 for i in num: 76 total += float(i) 77 return total 78 79 80 81 if __name__ == ‘__main__‘: 82 formula = "1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))" 83 result=calc(formula) 84 print(result)
标签:
原文地址:http://www.cnblogs.com/eric8899/p/5982178.html