利用正則表達式計算下面值:
1 - 2 * ( (60 - 30 + (-40.0/5) * (9 - 2 * 5/3 + 7 / 3 * 10/4*2 +10 *5/14)) -(-4*3)/(16-3*2))
import re
def wipe(s): #定義去除重復+-號函數
res=s.replace("+-","-").replace("++","+").replace("--","+").replace("-+","-")
return res
def get(s):#定義取括號內運算式函數
res=re.sub(" ","",s)#去除字符之間的空格
res1 = re.split("\(([^()]+)\)", res,1)#取最里面的括號的運算式
return res1
def add_num(s):#定義加減運算函數
s=wipe(s)#進行加減法運算前執行去重+-號
num = re.findall("([+\-]?\d+\.?\d*)", s)#取到所有數字的列表num
k=0
for i in num:
k+=float(i)
return k #進行循環相加減並返回最后值
def mul(s):#定義乘除法運算
while True:
res=re.split("(\d+\.?\d*[\*/][\+-]?\d+\.?\d*)", s,1) #將整個運算式以最里面的運算式為中間部分分成三個元素的列表
if len(res)==3 and "*"in res[1]:#判斷列表元素是否為三個以及*號是否在最中間運算式里
a,b,c=res#分別取到列表里的元素的值
d,e=b.split("*")#將最里面的運算式以*進行分割取到兩邊的值
res_s=float(d)*float(e)#將兩邊的值進行運算
s = a+str(res_s)+c#將結果替換原來的運算式
elif len(res)==3 and "/"in res[1]:#判斷列表元素是否為三個以及/號是否在最中間運算式里
a,b,c=res
d,e= b.split("/")#將最里面的運算式以/進行分割取到兩邊的值
res_s=float(d)/float(e)
s=a+str(res_s)+c
else:#如果列表元素小於三直接進行加減法運算
return add_num(s)
def counter(s): #定義計算器函數
while True:
res=get(s)#進行取值並判斷
if len(res)==3:#如果取到的值的列表元素是三進行乘除運算
a,b,c=res
result=mul(b)
s = a + str(result) + c#將最后的乘除運算結果替換原來的運算式
else:
return mul(s) #如果列表元素小於三直接進行加減法運算
a="1 - 2 * ( (60 - 30 + (-40.0/5) * (9 - 2 * 5/3 + 7 / 3 * 10/4*2 +10 *5/14)) -(-4*3)/(16-3*2))"
print(counter(a))