1 import re 2 formul='2*(1+2*6/3-2)+5+2*(1+6/2/3-2)' 3 4 def addjian(func): 5 digital = re.split('(\D)',func) 6 for index in range(1,len(digital),2): ...
1 import re 2 formul='2*(1+2*6/3-2)+5+2*(1+6/2/3-2)' 3 4 def addjian(func): 5 digital = re.split('(\D)',func) 6 for index in range(1,len(digital),2): 7 if digital[index] == '+': 8 digital[index + 1] = str(int(digital[index - 1]) + int(digital[index + 1])) 9 elif digital[index] == '-': 10 digital[index + 1] = str(int(digital[index - 1]) - int(digital[index + 1])) 11 12 return digital[-1] 13 def chengchu(func): 14 ret = re.findall('\d+[^+-]+\d',func) 15 for i in ret: 16 digital = re.split('(\D)',i) #加個括弧是為了優先順序的原因,保留非數字 17 for index in range(1,len(digital),2):##這個地方的思想很巧妙,假設[1,/,2,*,3,/,4,*,5], 18 # 我會把1/2的結果替換到2的身上位0.5,然後,0.5*3的結果替換到3的身上,最終結果取最後一個。。。 19 if digital[index] == '*' : 20 digital[index+1] = str(int(digital[index-1])*int(digital[index+1])) 21 elif digital[index] == '/' : 22 digital[index + 1] = str(int(digital[index - 1]) //int(digital[index + 1])) 23 func = re.sub('\d+[^+-]+\d',digital[-1],func,1) 24 return func 25 print(ret) 26 a=1 27 28 def comput(formal): 29 re.sub('\s','',formal) 30 while(not formal.isdigit()): 31 ret = re.findall('\(([^()]*)\)',formal) 32 print(ret) 33 if ret: 34 for i in ret: 35 if '*'in i or '/' in i: 36 result_chengchu = chengchu(i)#先算乘除 37 else: 38 result_chengchu = i 39 if '+'in result_chengchu or '-' in result_chengchu: 40 result_addjian = addjian(result_chengchu)#再算加減 41 else: 42 result_addjian = result_chengchu 43 44 formal = re.sub('\(([^()]*)\)',str(result_addjian),formal,1) 45 else: 46 if '*' in formal or '/' in formal: 47 result_chengchu = chengchu(formal) # 先算乘除 48 else: 49 result_chengchu = formal 50 if '+' in result_chengchu or '-' in result_chengchu: 51 result_addjian = addjian(result_chengchu) # 再算加減 52 else: 53 result_addjian = result_chengchu 54 formal = result_addjian 55 print(formal) 56 57 comput(formul)View Code