简体   繁体   中英

Error in concatenating lists and string for recursion (Postfix to Infix)

I'm writing a code that uses recursion to convert postfix to infix expressions. I keep getting errors that state that my list is out of range in my if statements, and that I can't concatenate str and lists. If you can give me some tips for indexing as well, that would be great. Thank you!

def Post_to_In_Recursion(expression):
  if len(expression) == 1: 
    return expression
  else: 
    operator = 0 
    operand = 0
    position = -1
    while operator > operand: 
      if isOperand(expression[position]):
        operand += 1
      else: 
        operator += 1
      position = position - 1
    return '(' + Post_to_In_Recursion(expression[:position])+ Post_to_In_Recursion(expression[-1]) + Post_to_In_Recursion(expression[position:]) + ')'
                                                                                                                                
def isOperand(char):
  if (char >= "a" and char <= 'z') or (char >= 'A' and char <= 'Z'):
    return True
  else: 
    return False

expression = ['a','b','*','c','+'] 
print(Post_to_In_Recursion(expression))

Your problem there is that you're trying to concatenate strings with lists in line 14. To solve the problem, you have to convert the lists into strings with str() .

I once had the same project, a program to find infix for a given postfix. And I did it this way:

def isOperand(x):
    return ((x >= 'a' and x <= 'z') or
        (x >= 'A' and x <= 'Z'))

# Get Infix for a given postfix expression
def getInfix(exp) :
    s = []
    for i in exp:   
        # Push operands
        if (isOperand(i)) :     
            s.insert(0, i)
            
        # We assume that input is a valid postfix and expect an operator
        else:
            op1 = s[0]
            s.pop(0)
            op2 = s[0]
            s.pop(0)
            s.insert(0, "(" + op2 + i + op1 + ")")
    return s[0]


if __name__ == '__main__':
    exp = "ab*c+" # Declare your expression here
    print(getInfix(exp.strip()))

Output:

((a*b)+c)

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