【发布时间】:2021-09-09 01:03:24
【问题描述】:
我已经使用 stack 实现了中缀到前缀的转换器,幂运算符具有从右到左的关联,这让我疯狂地尝试实现它。
这是我的代码:
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)
【问题讨论】:
-
你能详细说明你的问题吗?到底是什么不工作?
-
@ARK1375 我想在将表达式从中缀表示法转换为后缀表示法时处理幂运算符 (^)。
-
这段代码运行没有问题。
标签: python algorithm data-structures stack