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)