RPN(后缀表示法)当优先级较高的运算符位于其他运算符的右侧时,算法“中断”

2024-10-03 13:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写一个从中缀到后缀符号的转换器(当然,使用Shunting-Yard algorithm)。它似乎适用于以下情况:

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

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

^{pr2}$

也就是说,除非有括号,否则当优先级较高的运算符位于优先级较低的运算符的右侧时,它不会返回。在

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

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)

Tags: andintokenreturnifqueuestack运算符
1条回答
网友
1楼 · 发布于 2024-10-03 13:26:59

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

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

  • while there is an operator token, o2, at the top of the operator stack, and either
    • o1 is left-associative and its precedence is less than or equal to that of o2, or
    • o1 is right associative, and has precedence less than that of o2,

相关问题 更多 >