【问题标题】:RPN (postfix notation) algorithm "breaking" when operator with higher precedence is to the right of the others当具有较高优先级的运算符位于其他运算符的右侧时,RPN(后缀表示法)算法“中断”
【发布时间】:2015-06-27 06:24:25
【问题描述】:

我正在 Python 中制作从中缀到后缀表示法的转换器(当然,使用 Shunting-Yard algorithm)。它似乎适用于以下情况:

>>>rpn('9+6-5')
96+5+
>>>rpn('(5+6)/5')
56+5/
>>>rpn('5+(6/5)')
565/+

但是,只要函数接收到如下表达式,它就会起作用(不返回):

>>>rpn('5+6/5')
^C 
"something borke"

即,当优先级较低的运算符的右侧有较高优先级的运算符时,它不会返回,除非有括号。

这是我正在使用的完整代码。它似乎非常接近算法,但我可能错了。

def defop(x):
    return {'+': [2, 'left'], '-': [2, 'left'], '*': [3, 'left'], '/': [3, 'left'], '^': [4, 'right']}[x]       

def rpn(exp):
    stack, queue = [],[]
    try:
        if len(exp) > 0:
            for token in list(exp):
                if token in "+-*/^":
                    _o1 = defop(token)
                    while stack and stack[-1] in '+-*/&^':
                        _o2 = defop(stack[-1])
                        if _o1[1] == 'left' and _o1[0] <= _o2[0] or _o1[1] == 'right' and _o1[0] < _o2[0]:
                            queue.append(stack.pop())                       
                    stack.append(token)
                elif token == '(':
                    stack.append(token)
                elif token == ')':
                    for item in reversed(stack):
                        if item != '(':     
                            queue.append(stack.pop())           
                        else:       
                            stack.pop()
                            break
                else:
                    queue.append(token)
            while stack:
                if stack[-1] in '()':
                    return "Mismatched parentheses"
                queue.append(stack.pop())
    except:
        return 'something borke'
    return ''.join(queue)

【问题讨论】:

  • 您的规格有问题:您如何计算 12 + 3,并将其与 1 + 23 区分开来:如果我按照您的示例进行操作,两种情况下都应该是 123+ ...跨度>
  • 第一步是去掉空的except,这样你就可以实际进行一些调试(参见例如blog.codekills.net/2011/09/29/the-evils-of--except--)。 “something borke” 拼写正确时很有帮助。

标签: python postfix-notation


【解决方案1】:

当代码到达while 循环并且if 语句中的表达式计算结果为假时,会发生什么?

将您链接到的维基百科文章中的重要部分加粗:

  • 虽然在运算符堆栈的顶部有一个运算符令牌 o2,但 和任一
    • o1 是左结合的,它的优先级小于或等于 o2 的优先级,或者
    • o1 是右结合,优先级低于 o2,

【讨论】:

    猜你喜欢
    • 2011-08-30
    • 1970-01-01
    • 2021-10-25
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    相关资源
    最近更新 更多