Python 3.x python中的中缀到后缀:为什么我的程序不能弹出最后一个元素?
下面是我将中缀表达式转换为后缀表达式的实现Python 3.x python中的中缀到后缀:为什么我的程序不能弹出最后一个元素?,python-3.x,stack,postfix-notation,infix-notation,Python 3.x,Stack,Postfix Notation,Infix Notation,下面是我将中缀表达式转换为后缀表达式的实现 from ArrayStack import ArrayStack class Convertor: ''' Class to convert the Infix exp into Postfix exp''' def __init__(self,exp): ''' Constructor to initialize the class variable ''' self.infix = exp
from ArrayStack import ArrayStack
class Convertor:
''' Class to convert the Infix exp into Postfix exp'''
def __init__(self,exp):
''' Constructor to initialize the class variable '''
self.infix = exp
self.stack = ArrayStack(len(exp))
def is_operand(self,sym):
''' Check if symbol is operand '''
return sym.isalpha()
def precedence(self,sym):
''' Returns the precedence of the operator'''
if sym == '+' or sym == '-':
return 1
elif sym == '*' or sym =='/':
return 2
elif sym == '^':
return 3
else:
return -1
def infix_to_postfix(self):
''' Converts the inifx exp into postfix exp '''
postfix = []
for i in self.infix:
if self.is_operand(i):
postfix.append(i)
elif i == '(':
self.stack.push(i)
elif i == ')':
while(not self.stack.is_empty() and self.stack.top() !='('):
postfix.append(self.stack.pop())
self.stack.pop()
else:
while (not self.stack.is_empty() and self.precedence(i) <= self.precedence(self.stack.top())):
postfix.append(self.stack.pop())
self.stack.push(i)
while (not self.stack.is_empty):
postfix.append(self.stack.pop())
postfix.append(self.stack.pop()) # I don't know why an element still existing in the stack , can any one help
print(postfix,len(postfix))
if __name__ == '__main__':
exp = "a+b*(c^d-e)^(f+g*h)-i"
print(exp,len(exp))
convertor = Convertor(exp)
convertor.infix_to_postfix()
从ArrayStack导入ArrayStack
类转换器:
''类将中缀表达式转换为后缀表达式''
定义初始化(self,exp):
''构造函数初始化类变量''
self.infix=exp
self.stack=ArrayStack(len(exp))
def是操作数(self,sym):
''检查符号是否为操作数''
返回符号isalpha()
def优先级(自身,sym):
''返回运算符''的优先级'
如果sym='+'或sym='-':
返回1
elif sym=='*'或sym=='/':
返回2
elif sym=='^':
返回3
其他:
返回-1
def中缀到后缀(自):
''将inifx exp转换为后缀exp''
后缀=[]
对于self.infix中的i:
如果self.is_操作数(i):
postfix.append(一)
elif i=='(':
self.stack.push(一)
如果i==')':
while(非self.stack.is_empty()和self.stack.top()!='('):
postfix.append(self.stack.pop())
self.stack.pop()
其他:
while(不是self.stack.is_empty()和self.priority(i)