[英]Error in concatenating lists and string for recursion (Postfix to Infix)
我正在编写一个使用递归将后缀转换为中缀表达式的代码。 我不断收到 state 的错误,即我的列表超出了 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))
您的问题是您尝试将字符串与第 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()))
Output:
((a*b)+c)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.