aur*_*del 2 algorithm infix-notation postfix-notation python-3.x
对于我的数据结构类,我必须使用 Python 3 创建一个基本的图形计算器。要求是我们必须使用一个基本的 Stack 类。用户以“中缀”形式输入方程,然后我应该将其转换为“后缀”以进行评估和绘图。我在使用中缀到后缀算法时遇到问题。我见过其他可以工作的算法,但我的教授希望它以某种方式完成。这是我到目前为止所拥有的:
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
Run Code Online (Sandbox Code Playgroud)
当我打印这个时,当预期结果是 '3x1+*22/-' 时,我得到 '3x1+22' 任何帮助将不胜感激。谢谢。
小智 8
退出循环后,您应该弹出堆栈中剩余的操作数。该算法非常简单,但如果您需要信息,请在此处解释:
http://interactivepython.org/runestone/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html
如果您需要,这是我的解决方案版本:)
def toPostfix(infix):
stack = []
postfix = ''
for c in infix:
if isOperand(c):
postfix += c
else:
if isLeftParenthesis(c):
stack.append(c)
elif isRightParenthesis(c):
operator = stack.pop()
while not isLeftParenthesis(operator):
postfix += operator
operator = stack.pop()
else:
while (not isEmpty(stack)) and hasLessOrEqualPriority(c,peek(stack)):
postfix += stack.pop()
stack.append(c)
while (not isEmpty(stack)):
postfix += stack.pop()
return postfix
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26591 次 |
| 最近记录: |