import re s = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )' # 計算乘除返回值 # 1.使用'*'或者'/'切割,拿到a,b # 2.計算浮點數a,b結果,返回結果 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 # 使用正則拿到乘除法算式,再使用atom_exp函數計算乘除法結果,並返回結果 # 1.使用re模塊的search方法,篩選乘除法,正則表達式:\d+(\.\d+)?[*/]-?\d+(\.\d+)? # 2.調用atom_cal函數計算拿到篩選後的乘除算式 # 3.將計算結果替換到原算式位置 # 4.返回計算完結果 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) exp = exp.replace(atom_exp,res) else: return exp # 使用正則拿到加減進行加減運算 # 1.使用re模塊的findall方法,篩選加減法,正則表達式:[+-]?\d+(?:\.\d+)? # 2.建立結果變量 # 3.拿到全部算式,結果相加 def add_sub(exp): ret = re.findall('[+-]?\d+(?:\.\d+)?',exp) exp_sum = 0 for i in ret: exp_sum += float(i) return exp_sum # 計算每一個算式的結果 # 1.調用乘除法函數(mul_div),先算乘除結果 # 2.格式化計算符號(--/+-/-+/++),方便加減計算 # 3.調用加減法函數(add_sub),計算加減 # 4.返回計算結果 def cal(exp): exp = mul_div(exp) exp = format_exp(exp) exp_sum = add_sub(exp) return exp_sum # 主函數 # 1.去空格 # 2.使用正則拿到全部括號內的算式,正則表達式:\([^()]+\) # 3.經過re模塊的search方法分別取每一個算式 # 4.讓拿到的括號中的每一個算式使用cal函數進行計算 # 5.將計算的結果替換到原算式位置 # 6.解決最外層計算符號 # 7.返回最終計算結果 def main(exp): exp = exp.replace(' ','') while True: ret = re.search('\([^()]+\)',exp) if ret: inner_bracked = ret.group() res = str(cal(inner_bracked)) exp = exp.replace(inner_bracked,res) exp = format_exp(exp) else: break return cal(exp) ret = main(s) print(ret) print(eval(s))