python實現字串計算機

來源:互聯網
上載者:User

標籤: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實現字串計算機

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.