[英]Evaluating postfix using stack python
我的任務是轉換帶括號的中綴表達式。 例
((((54 + 56)+(4 + 73))+(9 + 7))
后綴。 然后評估后綴。 該表達式是從用戶輸入的。 我必須使用已經為我編寫的名為Stack的類。 不得修改:
class Stack:
def __init__(self):
self.theStack=[]
def top(self):
if self.isEmpty():
return "Empty Stack"
else:
return self.theStack[-1]
def isEmpty(self):
return len(self.theStack)==0
def push(self,item):
self.theStack.append(item)
def pop(self):
if not self.isEmpty():
temp=self.theStack[-1]
del(self.theStack[-1])
return temp
else:
return "Empty Stack"
我遇到的第一個問題是,當用戶輸入例如54時,在使用堆棧時,5和4是兩個不同的元素。 如何將它變成一個?
這是我到目前為止評估后綴的代碼:
OPERATOR=["+","-","*", "/"]
def evaluatePostfix(Postfix):
eStack=Stack()
for n in Postfix:
if n not in OPERATOR and n!="(" and n!=")":
eStack.push(n)
if n in OPERATOR:
math=eStack.pop()+n+eStack.pop()
eval(math)
我知道問題是倒數第二行,但是我不確定如何解決
您要問幾個問題(就引導您達到評估后綴表達式的最終目標而言,您的答案還不完整),但讓我解決您所提出的問題:
“我遇到的第一個問題是,當用戶輸入例如54時,在使用堆棧時,5和4是兩個不同的元素。如何將其變成一個?”
如果您承諾一次掃描輸入的一個字符,那么最簡單的方法是使用一個臨時變量。 這是在Python中執行此操作的快速而骯臟的方法。
infix = "54 + 490"
postfix = ""
a_number = None
OPERATOR = ["+", "-", "*", "/"]
for n in infix:
if n not in OPERATOR and n != "(" and n != ")":
if a_number is None:
a_number = n
else:
a_number = a_number + n
if n is ")" or n in OPERATOR:
if a_number is not None:
postfix += a_number
a_number = None
if a_number is not None:
postfix += a_number
a_number = None
print postfix
當你寫:
for n in Postfix
您一次遍歷Postfix中的字符。 您可能最好通過以下幾行使用輔助函數將Postfix轉換為字符串列表,以填充運算符(如果未填充)
def foo(str):
newstr = ""
for x in str:
if x not in "0123456789. ":
newstr += " " + x + " "
else:
newstr += x
return newstr
所以現在你可以改變
for n in Postfix
至
for n in foo(Postfix).split()
並且應該解決不能正確處理數字的問題。
split()將字符串拆分為非空白字符串列表,例如,“ hello world”將變為[“ hello”,“ world”]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.