正则匹配运算 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、循环执行前两步的结果

  



import re # 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))" # #含义:匹配括号,但是不匹配成对的括号,按正则表达式进行分割,最大分割次数为1次,取出最内层的括号内的一组元素 # val = re.split('\(([^()]+)\)',formula,1) # before,center,last=val # print(val) # #将取出的内容进行运算 # if "*" in center: # new_center=re.split("\*",center) # sub_res=float(new_center[0])*float(new_center[1]) # print("单步计算结果为:",sub_res) # # elif "/" in center: # new_center=re.split("/",center) # sub_res=float(new_center[0])/float(new_center[1]) # print("单步计算结果为:",sub_res) # # formula=before+str(sub_res)+last # print(formula) # val1 = re.split('\(([^()]+)\)',formula,1) # print(val1) # val2= re.split('(\d+\.?\d*[*/][\-]?\d+\.?\d*)',formula,1) # print("val2:",val2) # before1,center1,last1=val2 # # if "*" in center1: # new_center=re.split("\*",center1) # print("111:",new_center) # sub_res=float(new_center[0])*float(new_center[1]) # print("单步计算结果为:",sub_res) # # elif "/" in center1: # new_center=re.split("/",center1) # sub_res=float(new_center[0])/float(new_center[1]) # print("单步计算结果为:",sub_res) #计算,首先利用正则表达式,匹配最内层括号,并取出最内层括号内的元素,然后进行最内层括号内运算 def calc(formula): while True: #取最里层括号里面的内容,进行运算 val =re.split('\(([^()]+)\)',formula,1) if len(val)==3: before,center,last=val new_center=mul_div(center) formula=before+str(new_center)+last else: return mul_div(formula) def mul_div(formula): while True: #取优先级高的,进行拆分计算 val1=re.split('(\d+\.?\d*[*/][\-]?\d+\.?\d*)',formula,1) if len(val1)==3: bef,cent,la=val1 if "*" in cent: new_cent=re.split("\*",cent) sub_res=float(new_cent[0])*float(new_cent[1]) formula=bef+str(sub_res)+la elif "/" in cent: new_cent=re.split("/",cent) sub_res=float(new_cent[0])*float(new_cent[1]) formula=bef+str(sub_res)+la else: return final(formula) def final(formula): #由前面的分析结果可以看出,拆分时运算符被拆分,但计算结果有时含有运算符,故需进行替换 formula = formula.replace('++','+').replace('+-','-').replace('-+','-').replace('--','+') num = re.findall('[+\-]?\d+\.?\d*',formula) total = 0 for i in num: total += float(i) return total if __name__ == '__main__': 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))" result=calc(formula) print(result)

  

猜你喜欢

转载自www.cnblogs.com/huangjiangyong/p/10926920.html
今日推荐