【问题标题】:Error in concatenating lists and string for recursion (Postfix to Infix)连接列表和字符串以进行递归时出错(后缀到中缀)
【发布时间】:2021-07-01 05:53:37
【问题描述】:

我正在编写一个使用递归将后缀转换为中缀表达式的代码。我不断收到错误消息,指出我的列表超出了 if 语句的范围,并且我无法连接 str 和列表。如果您也可以给我一些索引提示,那就太好了。谢谢!

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

【问题讨论】:

  • 输出应该看起来像((a*b)+c),对吧?

标签: python python-3.x list recursion


【解决方案1】:

您的问题是您尝试将字符串与第 14 行中的列表连接起来。要解决此问题,您必须使用 str() 将列表转换为字符串。

我曾经有过同样的项目,一个为给定后缀查找中缀的程序。我是这样做的:

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

输出:

((a*b)+c)

【讨论】:

  • 我尝试使用 str 进行类型转换,但它给出了递归达到限制的错误。我的项目需要递归问题。
  • 你可以更改python设置的默认递归限制sys:例如import sys sys.setrecursionlimit(10**6)
猜你喜欢
  • 2021-06-09
  • 2014-05-08
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
  • 2015-06-21
  • 1970-01-01
  • 2017-04-20
  • 2021-06-25
相关资源
最近更新 更多