使用递归的后缀到中缀
Postfix to Infix using Recursion
我想使用递归制作一个后缀到中缀的转换器。这是我的代码,没有使用递归,只是循环。
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))
有什么建议吗?
这取决于使用递归的原因,但如果你只是想要一个递归解决方案,这应该可行
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, []))
我想使用递归制作一个后缀到中缀的转换器。这是我的代码,没有使用递归,只是循环。
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))
有什么建议吗?
这取决于使用递归的原因,但如果你只是想要一个递归解决方案,这应该可行
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, []))