【问题标题】:Postfix to Infix using Recursion使用递归的后缀到中缀
【发布时间】:2021-06-09 14:05:36
【问题描述】:

我想使用递归制作一个后缀来中缀转换器。这是我的代码,没有使用递归,只是循环。

def to_Infix(expression):
  stack = []
  for x in range(len(expression)):
    if isOperand(expression[x]):
      stack.append(expression[x])
    else: 
      operator1 = stack.pop()
      operator2 = stack.pop()
      stack.append('(' + operator2 + expression[x] + operator1 + ')')
  return stack.pop()
 
def isOperand(char):
  if (char >= "a" and char <= 'z') or (char >= 'A' and char <= 'Z'):
    return True
  else: 
    return False
 
expression = ['a','b','*','c','+','d','*','e','/'] 
print(to_Infix(expression))

有什么建议吗?

【问题讨论】:

    标签: python python-3.x list recursion stack


    【解决方案1】:

    这取决于使用递归的原因,但如果你只是想要一个递归解决方案,这应该可行

    def toInfixRec(expression, position, stack):
        if position == len(expression):
            return stack.pop()
        
        if isOperand(expression[position]):
            stack.append(expression[position])
        else:
            operator1 = stack.pop()
            operator2 = stack.pop()
            stack.append('({0}{1}{2})'.format(operator2, expression[position], operator1))
            
    
        return toInfixRec(expression, position + 1, stack)
    
    print(toInfixRec(expression, 0, []))
    

    【讨论】:

    • 非常感谢!这非常有帮助。
    猜你喜欢
    • 1970-01-01
    • 2013-02-26
    • 2015-06-14
    • 2012-04-05
    • 2020-10-03
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多