无法扩展中缀到前缀转换器以处理电源 (^) 运算符



我已经使用堆栈实现了中缀到前缀转换器,幂运算符有从右到左的关联,这让我很难实现它。

这是我的代码:

def infix_to_postfix_converter(string):
def pop_untill_open_parentheses():
while not stack.is_empty() and stack.peek() != '(':
output.append(stack.pop())
stack.pop()
def pop_all_the_higher_precedences(operator):
while not stack.is_empty() and precedence(stack.peek()) >= precedence(operator):
if stack.peek() != '(':
output.append(stack.pop())
else:
break
stack.push(operator)
def precedence(operator):
operators = {'(': 3,
')': 3,
'^':2,
'*': 1,
'/': 1,
'+': 0,
'-': 0,
}
return operators[operator]
stack = Stack()
output = []
for literal in string:
if literal.isalpha():
output.append(literal)
elif literal == '(':
stack.push(literal)
elif literal == ')':
pop_untill_open_parentheses()
else:
pop_all_the_higher_precedences(literal)
while not stack.is_empty():
output.append(stack.pop())
return ''.join(output)

所以解决方案是,如果堆栈中有一个"^",并且要推送另一个"^",它将被推送到第一个"^'"的顶部,而不弹出它。

我的解决方案:

添加此比较功能:

def compare(operatora,operatorb):
if operatora==operatorb=='^':
return False
else:
return precedence(operatora)>=precedence(operatorb)

修改pop_all_the_higher_priorience函数:

def pop_all_the_higher_precedences(operator):
while not stack.is_empty() and compare(stack.peek(),operator):
if stack.peek() != '(':
output.append(stack.pop())
else:
break
stack.push(operator)

最新更新