[英]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.