python練習(xí)作業(yè)...
import math, re string = "1.5 - 2.4 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )" string = ''.join(string.split()) #字符串去空格 #字符串格式化 def stringFormat(string): string = string.replace('--', '+') string = string.replace('-', '+-') string = string.replace('*+-', '*-') string = string.replace('/+-', '/-') return string #不含括號字符串公式計算函數(shù) def stringCalculate(string): fResult = 0.0 # 浮點型計算結(jié)果 tmpListAdd = list() # 加減法列表 #公式數(shù)據(jù)拆分 strList = stringFormat(string).split('+') #第一步先根據(jù)加法將字符串分段,如果分段內(nèi)含有乘除法,則進入乘除法分段計算,否則轉(zhuǎn)化成浮點數(shù),存入列表 for inLoopAdd in strList: #第一層循環(huán)---加減法分割 #乘法模塊 if'*' in inLoopAdd or '/' in inLoopAdd: tmpListMulti = list() #乘法列表 for inloopMulti in inLoopAdd.split('*'): #第二層----乘法分割 #除法模塊 if '/' in inloopMulti: divList = inloopMulti.split('/') fDivResult = float(divList[0]) for inloopDiv in range(len(divList)-1): #第三層-----內(nèi)層除法計算 fDivResult /= float(divList[inloopDiv+1]) tmpListMulti.append(fDivResult) else: tmpListMulti.append(float(inloopMulti)) fMultiResult = 1 for inloop in tmpListMulti: fMultiResult *= inloop tmpListAdd.append(fMultiResult) elif inLoopAdd: tmpListAdd.append(float(inLoopAdd)) #將各分段結(jié)果累加 for fAddResult in tmpListAdd: fResult += fAddResult return str(fResult) #去括號 while('(' in string): temString = re.search('\([0-9+\-*./]*\)', string).group() string = string.replace(temString, stringCalculate(temString[1:-1])) print(stringCalculate(string))
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。