Python3實現逆波蘭表示式計算

2021-07-31 09:57:40 字數 4826 閱讀 2321

importlogging

logging.basicconfig(level=logging.info)

importre

##判斷字串是否為小數

defisnumber(num):

regex = re.compile(r"^(-?\d+)(\.\d*)?$")

ifre.match(regex,num):

return trueelse:

return false#

自定義棧

classpystack(object):

def__init__(self,initsize=20,incsize=10):

self.initsize=incsize

self.incsize=incsize

self.stacklist=

self.top=self.bottom=0

defpush(self,ele):

ifself.top-self.bottom>=self.initsize:

self.incsize+=self.initsize

self.top+=1

defpop(self):

ifself.top-self.bottom>0:

self.top-=1

ret=self.stacklist.pop()

returnret

else:

return nonedeflen(self):

returnself.top-self.bottom

##算式轉化為中綴表示式列表

defequation2list():

equation=input("請輸入你要運算的方程:")

result=

buffnum=

foriinequation:

ifi.isdigit()ori=='.':

else:

iflen(buffnum)>0:

.join(buffnum))

buffnum.clear()

iflen(buffnum)>0:

.join(buffnum))

buffnum.clear()

logging.info(result)

returnresult

##中綴表示式轉字尾表示式

## 1+2*(3+4)=15

##1 2 3 4 + * +

defmid2endsuffix(list):

resultlist=

stack=pystack()

foriinlist:

ifisnumber(i):

elif')'== i:

whilestack.len()>0:

item=stack.pop()

logging.debug(")pop==%s"%(item))

if'('==item:

breakelse:

elif'+'== ior'-'== i:

ifstack.len() == 0:

stack.push(i)

logging.debug("+-none=push==%s"%i)

else:

whilestack.len()>0:

item2=stack.pop()

logging.debug("+-=pop==%s"%item2)

if'('== item2:

stack.push(item2)

logging.debug("+-=(push==%s"%item2)

breakelse:

stack.push(i)

logging.debug("+-lastpush==%s"%i)

elif'*'== ior'/'== ior'('== i:

stack.push(i)

logging.debug("*/(push==%s"%i)

else:

print("輸入格式有誤")

whilestack.len()>0:

item3=stack.pop()

logging.debug("last==pop=%s"%item3)

returnresultlist

##字尾表示式計算結果

defcalendsuffixresult(list):

stack=pystack()

sumend=0

iflen(list)==0:

returnsumend

foriinlist:

ifisnumber(i):

stack.push(float(i))

elif'+'==i:

a=stack.pop()

b=stack.pop()

stack.push(b+a)

elif'-'==i:

a = stack.pop()

b = stack.pop()

stack.push(b - a)

elif'*'==i:

a = stack.pop()

b = stack.pop()

stack.push(b * a)

elif'/'==i:

a = stack.pop()

b = stack.pop()

ifa==0:

print('%d/%d分子不能為0'%(b,a))

else:

stack.push(b/a)

returnstack.pop()

if__name__=='__main__':

elist=equation2list()

midelist=mid2endsuffix(elist)

logging.info(midelist)

lastresult=calendsuffixresult(midelist)

print("算式的結果是:",lastresult)

目前程式還有個缺陷,控制台輸入的數字一般是斜體,如果是直體會無法識別。
暫時不清楚為啥會出現直體的情況,如果有知道的同學可以解答下

波蘭表示式 逆波蘭表示式

中綴表示式是最常見的運算表示式,如 3 5 2 6 1 波蘭表示式又稱為字首表示式,它是由中綴表示式經過一定的方式轉換來的 比如中綴表示式為 3 5x 2 6 1 對應的字首表示式為 3 x 5 2 6 1 對於中綴表示式從右向左遍歷轉換為字首表示式,中途要是用棧進行儲存 轉換規則如下 波蘭表示式 ...

波蘭逆波蘭表示式

實現乙個基本的計算器來計算簡單的表示式字串。表示式字串只包含非負整數,算符 左括號 和右括號 整數除法需要 向下截斷 你可以假定給定的表示式總是有效的。所有的中間結果的範圍為 231,231 1 class solution s2.push s.substr l,r l l r 碰見符號 else ...

波蘭表示式與逆波蘭表示式

2018年09月03日 11 29 15 jitwxs 閱讀數 70 標籤 波蘭 字首 更多 個人分類 演算法與資料結構 常見的算術表示式,稱為中綴表示式,例如 5 6 4 2 3波蘭表示式也稱為字首表示式,以上面的例子為例,其波蘭表示式為 5 6 4 2 3中綴表示式轉換字首表示式的操作過程為 1...