为什么我的评估逆波兰表示法不起作用?

-1 python algorithm math

这是我的代码,我的测试用例失败了:

["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Run Code Online (Sandbox Code Playgroud)

我打印了堆栈,堆栈如下所示:

[10]
[10, 6]
[10, 6, 9]
[10, 6, 9, 3]
[10, 6, 12]
[10, 6, 12, -11]
[10, 6, -132]
[10, -1] <-- ??
[-10]
[-10, 17]
[7]
[7, 5]
[12]
Run Code Online (Sandbox Code Playgroud)

当我们到达 -132, 6 时,它应该返回 0。不过不确定为什么它返回 -1,我尝试了其他它可以工作的编译器。所以我的问题是,发生了什么事?

def evalRPN(self, tokens):
    setOfOperator = {'+', '*', '/', '-'}
    def evaluate(x1, x2, operand):
        if operand == "+":
            return x1 + x2
        elif operand == '-':
            return x2 - x1  # Reverse order for subtraction
        elif operand == '*':
            return x1 * x2
        elif operand == '/':
            return int(x2 / x1)  # Reverse order for division

    stack = []
    
    for char in tokens:
        if char not in setOfOperator:
            stack.append(int(char))
        else:
            stack.append(evaluate(stack.pop(),  stack.pop() , char))
    if stack:
        return stack[-1]
Run Code Online (Sandbox Code Playgroud)

slo*_*rop 5

为什么会发生这种情况

这是 Python 2 与 Python 3 的区别。

在 Python 2 中,该/运算符执行整数除法,并向负无穷大舍入。所以6/-132给了-1,当然int(6/-132)也给了-1

在Python 3中,/运算符执行浮点除法,因此6/-132也是如此-0.045。然后该int函数会截断小数, 也是int(6/-132)如此0

(注意,//Python 3 中的运算符进行整数除法, 也是如此int(6//-132)-1

您想要的结果是0(如 Python 3 中所示),但您的代码可能是针对 Python 2 运行的。

修复选项

升级!

首先,您的平台是否有办法可以在 Python 3 上运行代码?理想情况下是这样,因为 Python 2 自 2020 年以来已正式过时。

浮点数除法

如果您无法使用 Python 3,则可以强制进行浮点除法,这在 Python 2 和 Python 3 中表现一致:

elif operand == '/':
    return int(float(x2) / x1) 
Run Code Online (Sandbox Code Playgroud)

快速说明:

print int(6/-132)
print int(float(6)/-132)
Run Code Online (Sandbox Code Playgroud)

印刷:

-1
0
Run Code Online (Sandbox Code Playgroud)

将 Python 3 的除法向后移植到 Python 2

或者,如果您运行的平台允许,您可以使用以下命令让 Python 2 实现 Python 3 风格/

from __future__ import division
Run Code Online (Sandbox Code Playgroud)

另一个快速说明:

from __future__ import division
print int(6/-132)
Run Code Online (Sandbox Code Playgroud)

印刷:

0
Run Code Online (Sandbox Code Playgroud)