標籤:res 去掉 else get bsp strip logs class enum
看兄弟連的Alex視頻提到一題作業:計算字串 "1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )"()不可以用eval)
我試了下,實現思路可能稍微有點複雜,不過代碼不是很複雜,僅做參考。
import redef get_parentheses(s):s = s.replace(‘ ‘,‘‘) #空格去掉#print(s)#print("====================")while True:L = re.findall("\([+\-\*/\d\.]+\)", s) #找到所有最內層的括弧if L:for i in L:tmp = i.strip(‘()‘)result = get_multiplicative_division(tmp)s = s.replace(i,result)s = s.replace(‘+-‘,‘-‘)s = s.replace(‘--‘,‘+‘)#print(s)#print("====================")else:s = get_multiplicative_division(s)breakreturn s""" get_multiplicative_division函數用來計算無括弧的運算式,實現思路應該能理解"""def get_multiplicative_division(s):num_list = re.findall(‘[\-]?[\d\.]+‘,s)sign_list = re.findall(‘[+\*/]‘,s)for i, s in enumerate(num_list):if ‘-‘ in s and i >0 and len(sign_list)<len(num_list)-1:sign_list.insert(i - 1,‘+‘)for i, s in enumerate(sign_list):if s ==‘*‘ :num_list[i+1] = float(num_list[i]) * float(num_list[i+1])num_list[i] = 0elif s == ‘/‘:num_list[i+1] = float(num_list[i]) / float(num_list[i+1])num_list[i] = 0else:continueresult = 0for i in num_list:result += float(i)return str(result)if __name__ == ‘__main‘:s = "1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )"print(get_parentheses(s))
其實,個人覺得實現方法很多,只是實現思路不同而已。
python實現字串計算機