简体   繁体   中英

Postfix to Infix using Recursion

I want to make a postfix to infix converter using recursion. Here is my code without using recursion, just loops.

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

Any tips?

It depends on the reason for using recursion, but if you just want a recursive solution, this should work

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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