Algorithm python中的中缀到后缀算法
对于我的数据结构类,我必须使用Python3创建一个基本的图形计算器。要求是我们必须使用一个基本的堆栈类。用户以“中缀”形式输入等式,然后我将其转换为“后缀”进行计算和绘图。我在中缀到后缀的算法上遇到了问题。我见过其他可以工作的算法,但我的教授希望它以某种方式完成。以下是我目前掌握的情况:Algorithm python中的中缀到后缀算法,algorithm,python-3.x,postfix-notation,infix-notation,Algorithm,Python 3.x,Postfix Notation,Infix Notation,对于我的数据结构类,我必须使用Python3创建一个基本的图形计算器。要求是我们必须使用一个基本的堆栈类。用户以“中缀”形式输入等式,然后我将其转换为“后缀”进行计算和绘图。我在中缀到后缀的算法上遇到了问题。我见过其他可以工作的算法,但我的教授希望它以某种方式完成。以下是我目前掌握的情况: def inFixToPostFix(): inFix = '3*(x+1)-2/2' postFix = '' s = Stack() for c in inFix: # if elif chain
def inFixToPostFix():
inFix = '3*(x+1)-2/2'
postFix = ''
s = Stack()
for c in inFix:
# if elif chain for anything that c can be
if c in "0123456789x":
postFix += c
elif c in "+-":
if s.isEmpty():
s.push(c)
elif s.top() =='(':
s.push(c)
elif c in "*/":
if s.isEmpty():
s.push(c)
elif s.top() in "+-(":
s.push(c)
elif c == "(":
s.push(c)
elif c == ")":
while s.top() is not '(':
postFix += s.pop()
s.pop()
else:
print("Error")
print(postFix)
return postFix
当我打印此文件时,当预期结果为“3x1+*22/-”时,我得到“3x1+22”
任何帮助都将不胜感激。谢谢。退出循环后,应该在堆栈上弹出剩余的操作数。该算法非常简单,但如果您需要信息,此处将解释: 如果您需要,这里是我的解决方案版本:)
为了使算法正确,需要对其进行大量修改
这是数据结构课程的初始任务之一,因为它真正认可了堆栈的使用。因此我不会分享我的代码,因为我认为你可以自己完成。仍然有困难,分享障碍,我将引导您到达目的地。您需要显示代码的输出,并解释输出如何与预期不符。这是我关于stackoverflow的第一篇文章。我甚至没有想到要把返回值和期望的返回值放在一起。谢谢您需要在转换结束时弹出堆栈,或者可以在调用中缀到后缀函数之前在整个表达式周围加上括号。你明白为什么这两种解决方案是等价的吗?谢谢!在你的代码和你发布的链接之间,我已经做了一些工作,我只是在做一些bug修复。如果输入像(10+20)*30,我怀疑你的代码是否可以正常工作?我试着运行你提供的链接,但我没有正确打印它,因为字符串读取不好。我的建议是首先删除所有空格,然后在操作符前后引入一个空格,然后进行拆分并继续for循环。这个词就是“算法”。它来源于某人的名字。不是“Algo”。
class stack:
def __init__(self):
self.item = []
def push(self,it):
self.item.append(it)
def peek(self):
if self.isempty() == True:
return 0
return self.item[-1]
def pop(self):
if self.isempty() == True:
return 0
return(self.item.pop())
def length(self):
return (len(self.item))
def isempty(self):
if self.item == []:
return True
else:
return False
def display(self):
if self.isempty()== True:
return
temps = stack()
while(self.isempty() != True):
x = self.peek()
print("~",x)
temps.push(x)
self.pop()
while(temps.isempty() != True):
x = temps.peek()
self.push(x)
temps.pop()
def isOperand(self, ch):
return ch.isalpha()
def notGreater(self, i):
precedence = {'+':1, '-':1, '*':2, '/':2, '%':2, '^':3}
if self.peek() == '(':
return False
a = precedence[i]
b = precedence[self.peek()]
if a <= b:
return True
else:
return False
def infixToPostfix(self, exp):
output = ""
for i in exp:
if self.isOperand(i) == True: # check if operand add to output
print(i,"~ Operand push to stack")
output = output + i
# If the character is an '(', push it to stack
elif i == '(':
self.push(i)
print(i," ~ Found ( push into stack")
elif i == ')': # if ')' pop till '('
while( self.isempty() != True and self.peek() != '('):
n = self.pop()
output = output + n
print(n, "~ Operator popped from stack")
if (self.isempty() != True and self.peek() != '('):
print("_________")
return -1
else:
x = self.pop()
print(x, "Popping and deleting (")
else:
while(self.isempty() != True and self.notGreater(i)):
c = self.pop()
output = output + c
print(c,"Operator popped after checking precedence from stack")
self.push(i)
print(i,"Operator pushed to stack")
# pop all the operator from the stack
while self.isempty() != True:
xx = self.pop()
output = output + xx
print(xx,"~ pop at last")
print(output)
self.display()
st = stack()
st.infixToPostfix("a+(b*c)")
class stack:
def __init__(self):
self.item = []
def push(self,it):
self.item.append(it)
def peek(self):
if self.isempty() == True:
return 0
return self.item[-1]
def pop(self):
if self.isempty() == True:
return 0
return(self.item.pop())
def length(self):
return (len(self.item))
def isempty(self):
if self.item == []:
return True
else:
return False
def display(self):
if self.isempty()== True:
return
temps = stack()
while(self.isempty() != True):
x = self.peek()
print("~",x)
temps.push(x)
self.pop()
while(temps.isempty() != True):
x = temps.peek()
self.push(x)
temps.pop()
def isOperand(self, ch):
return ch.isalpha()
def notGreater(self, i):
precedence = {'+':1, '-':1, '*':2, '/':2, '%':2, '^':3}
if self.peek() == '(':
return False
a = precedence[i]
b = precedence[self.peek()]
if a <= b:
return True
else:
return False
def infixToPostfix(self, exp):
output = ""
for i in exp:
if self.isOperand(i) == True: # check if operand add to output
print(i,"~ Operand push to stack")
output = output + i
# If the character is an '(', push it to stack
elif i == '(':
self.push(i)
print(i," ~ Found ( push into stack")
elif i == ')': # if ')' pop till '('
while( self.isempty() != True and self.peek() != '('):
n = self.pop()
output = output + n
print(n, "~ Operator popped from stack")
if (self.isempty() != True and self.peek() != '('):
print("_________")
return -1
else:
x = self.pop()
print(x, "Popping and deleting (")
else:
while(self.isempty() != True and self.notGreater(i)):
c = self.pop()
output = output + c
print(c,"Operator popped after checking precedence from stack")
self.push(i)
print(i,"Operator pushed to stack")
# pop all the operator from the stack
while self.isempty() != True:
xx = self.pop()
output = output + xx
print(xx,"~ pop at last")
print(output)
self.display()
st = stack()
st.infixToPostfix("a+(b*c)")
a ~ Operand push to stack
+ Operator pushed to stack
( ~ Found ( push into stack
b ~ Operand push to stack
* Operator pushed to stack
c ~ Operand push to stack
* ~ Operator popped from stack
( Popping and deleting (
+ ~ pop at last
abc*+