# 1 - 2 * ((60-30 +(-40.0/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2)))
# 通過Python實現,自動判斷括號以及加減乘除的運算優先級,得出運算結果,顯示運算步驟
import re def atom_cal(exp): if '*' in exp: #計算單個的乘法 a,b = exp.split('*') return str(float(a) * float(b)) elif '/' in exp: #計算單個的除法 a, b = exp.split('/') return str(float(a) / float(b)) def format_exp(exp): #處理符號的問題 exp = exp.replace('--','+') exp = exp.replace('+-','-') exp = exp.replace('-+','-') exp = exp.replace('++','+') return exp def mul_div(exp): #計算乘除法 while True: ret = re.search('\d+(\.\d+)?[*/]-?\d+(\.\d+)?',exp) #利用正則表達式匹配乘或除法 if ret: #如果匹配到的話 atom_exp = ret.group() #將這個值拿出來 res = atom_cal(atom_exp) #利用上面的atom_exp計算 exp = exp.replace(atom_exp,res) #將計算的結果把原來算法替換掉 else:return exp #如果匹配不到的話說明乘除法計算完畢,返回計算結果 def add_sub(exp): #計算加減法 ret = re.findall('[+-]?\d+(?:\.\d+)?', exp) #利用正則表達式算式中的帶符號的每項數字,返回一個列表 exp_sum = 0 for i in ret: exp_sum += float(i) #將列表中的每一項求和 return exp_sum def cal(exp): #計算加減乘除混合運算 exp = mul_div(exp) #調用mul_div函數先計算乘除法 exp = format_exp(exp) #調用format_exp處理計算時候的符號 exp_sum = add_sub(exp) #調用 add_sub計算加減法 return exp_sum # float #返回計算結果 def main(exp): exp = exp.replace(' ','') #刪除字符串中的空格 while True: ret = re.search('\([^()]+\)',exp) #匹配括號 if ret : #如果匹配到括號的話 inner_bracket = ret.group() #將匹配到的括號內容取出來 res = str(cal(inner_bracket)) #調用cal()計算括號中的內容,將返回結果轉換成字符串 exp = exp.replace(inner_bracket,res) #將匹配到的括號內容用計算器結果替換 exp = format_exp(exp) #處理符號 else:break #直到沒有括號跳出循環 return cal(exp) #將剩下的內容進行計算,然后返回 s = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )' ret = main(s) print(ret,type(ret))