不完善:1.若是公式裏沒()ui
2.算到中間部,可能有*-, +- ,-- ,這樣的狀況spa
import re '''計算字符串表達式''' bracket = re.compile('\([^()]+\)') # 查找最內層括號 div = re.compile('(\d+\.?\d*/-\d+\.?\d*)|(\d+\.?\d*/\d+\.?\d*)') # 查找除法運算 mul = re.compile('(\d+\.?\d*\*-\d+\.?\d*)|(\d+\.?\d*\*\d+\.?\d*)') # 查找乘法運算 add = re.compile('(-\d+\.?\d*\+\d+\.?\d*)|(\d+\.?\d*\+\d+\.?\d*)') # 查找加法運算 sub = re.compile('(-\d+\.?\d*-\d+\.?\d*)|(\d+\.?\d*-\d+\.?\d*)') # 查找減法運算 c_f=re.compile('\(?\d+\)?') strip=re.compile('[^()]') def Div(s): exp = re.split('/', div.search(s).group()) return s.replace(div.search(s).group(), str(float(exp[0]) / float(exp[1]))) def Mul(s): exp = re.split('\*', mul.search(s).group()) return s.replace(mul.search(s).group(), str(float(exp[0]) * float(exp[1]))) def Add(s): exp = re.split('\+', add.search(s).group()) return s.replace(add.search(s).group(), str(float(exp[0]) + float(exp[1]))) def Sub(s): exp = sub.search(s).group() if exp.startswith('-'): exp = exp.replace('-', '+') exp = exp.replace('+', '', 1) res = Add(exp) return s.replace(sub.search(s).group(), '-' + res) else: exp = re.split('-', sub.search(s).group()) return s.replace(sub.search(s).group(), str(float(exp[0]) - float(exp[1]))) def calc(): while True: s = input('請輸入等式').replace(' ','') if s=='quit': break else: while bracket.search(s): s_search=bracket.search(s).group() if div.search(s_search): s=s.replace(s_search,Div(s_search)) elif mul.search(s_search): s=s.replace(s_search,Mul(s_search)) elif sub.search(s_search): s = s.replace(s_search, Sub(s_search)) elif add.search(s_search): s=s.replace(s_search,Add(s_search)) elif c_f.search(s_search): s=s.replace(s_search,strip.search(s_search).group()) print(s) calc()