繁体   English   中英

使用递归的后缀到中缀

[英]Postfix to Infix using Recursion

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

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))

有小费吗?

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

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, []))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM