【问题标题】:Couldn't Extend the infix-to-prefix-convertor to handle the power (^) operator无法扩展中缀到前缀转换器以处理幂 (^) 运算符
【发布时间】: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


【解决方案1】:

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

我的解决方案:

添加此比较功能:

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

并修改pop_all_the_higher_precedence函数:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-21
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多