[英]Infix to Postfix Python: IndexError: pop from empty list.Doesnt Work on Digits more than one
我的代碼:
from StackClass import Stack
def postfixEval(postfix):
os = Stack()
tokenList = postfix
for token in tokenList:
if token in "0123456789":
os.push(int(token))
else:
op2 = os.pop()
op1 = os.pop()
result = doMath(token,op1,op2)
os.push(result)
return os.pop()
def doMath(op, op1, op2):
if op == "*":
return op1 * op2
elif op == "/":
return op1 / op2
elif op == "+":
return op1 + op2
else:
return op1 - op2
def pres(p):
if p is '(':
return 0
elif p is '+' or '-':
return 1
elif p is '*' or '/':
return 2
else:
return 99
def read(p):
if p is '(':
return left
elif p is ')':
return right
elif p is '+' or p is '-' or p is '*' or p is '%' or p is '/':
return operator
elif p is ' ':
return empty
else :
return operand
def infixtopostfix(infixexp):
for i in infixexp :
type = read(i)
if type is left :
outlst.append(i)
elif type is right :
next = outlst.pop()
while next is not '(':
postfix.append(next)
next = outlst.pop()
elif type is operand:
postfix.append(i)
elif type is operator:
p = pres(i)
while len(outlst) is not 0 and p <= pres(outlst[-1]) :
postfix.append(outlst.pop())
outlst.append(i)
elif type is empty:
continue
while len(outlst) > 0 :
postfix.append(outlst.pop())
return " ".join(postfix)
#MAIN PROGRAM
while True:
postfix = []
outlst = []
operator = -10
operand = -20
left = -30
right = -40
empty = -50
infixexp = raw_input("\nEnter the infix notation : ")
ifx = infixexp.split()
showpfx = infixtopostfix(ifx)
print "\nIt's postfix notation is \n"
print(showpfx)
print "\nThe answer to the postfix notation is: \n"
pfx = showpfx.split()
print postfixEval(pfx)
choice = raw_input("\nDo you want to continue?<1-Yes/0-No>: ")
if choice == '0':
break
這適用於(1 + 3)* 5但在(500 + 500)* 1000上給出此錯誤:
> Traceback (most recent call last): File "practice.py", line 117, in
> <module>
> print postfixEval(pfx) File "practice.py", line 13, in postfixEval
> op2 = os.pop() File "C:\Python27\StackClass.py", line 16, in pop
> return self.items.pop() IndexError: pop from empty list
返回后綴值后,我再次將其拆分,然后將其插入到評估函數中。 它確實適用於1位數字,但不適用於3位數字。 知道怎么了嗎? 謝謝!
if token in "0123456789":
匹配的只有串"0123456789"
,例如個位數, 12
, 789
...檢查一個真正的正整數,將實際的方法:
if token.isdigits():
(如果已經處理了負數,則嘗試轉換為整數並捕獲ValueError
)
暫且不談:我在討論時,最好告訴您代碼中接下來發生的事情:
is
在比較引用 。 雖然字符串實習對短字符串效果很好,但我不會依賴於此。 使用==
代替。
pres
還有一個嚴重的問題:
elif p is '+' or '-':
正在檢查p
是否為+
,但如果不是,則測試-
是否為“真”,即...始終。 因此,您的情況始終是正確的。
用in
在字符串上重寫它:
def pres(p):
if p == '(':
return 0
elif p in '+-':
return 1
elif p in '*/':
return 2
else:
return 99
並擺脫了所有支持==
的is
測試。 這樣可以避免意外(例外是像None
這樣的單例對象, is
是慣用的)
注意:在read
您是正確的(除了is
部分):
elif p is '+' or p is '-' or p is '*' or p is '%' or p is '/':
但是當然,它寫得更短更好:
elif p in '+-*%/':
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.