LeetCode Python 解释器给出与本地解释器不同的答案

问题描述 投票:0回答:1

我正在 LeetCode 上练习一些基于二分搜索的问题。我正在研究问题 1283(找到最小除数)。我的 python 代码每次都给出错误的答案。我决定使用本地调试器来查看哪里出错了,但出乎意料的是,我的本地调试器为相同的代码给出了正确的答案。我联系了一位已经在 CPP 中完成此题的朋友,并要求他从他的帐户运行我的代码,我的解决方案在 LeetCode 上被他的帐户接受。在发布这个问题时,我又看了一遍这个问题,发现在将第10行

s += math.ceil(i/mid)
更改为
s += -(-i//mid)
时(据我所知两者具有相同的含义),LeetCode从我的帐户本身接受了我的解决方案。有谁知道这是什么原因。我真的很好奇这个。

Leetcode 截图

这是我的代码

import math
class Solution(object):
    def smallestDivisor(self, nums, threshold):   
        l,r = 1,max(nums)
        div = float('inf')
        while l <= r:
            mid = (l+r)//2
            s = 0
            for i in nums:
                s += math.ceil(i/mid)
            if s <= threshold:
                div = mid
                r = mid - 1
            else: l = mid + 1
        return div

我将最后一行更改为

print(div)
以在本地调试器中运行。

python python-3.x binary-search pythoninterpreter
1个回答
0
投票

在您的屏幕截图中,您使用的是 Python 2。

使用Python 3编译器将给出正确的结果。

点击“Python”

enter image description here

选择“Python3”

enter image description here

使用 Python 3 运行时的结果

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.