python - LeetCode 762 为什么单独的代码在 Jupyter Notebook 中有效,而在 Leetcode 中无效

标签 python python-3.x binary primes

我正在研究 leetcode“762. 二进制表示中设置位的质数”,并且我测试了我的代码在 Jupiter Notebook 上运行良好,当我迁移到 leetcode 时,它​​显示 null 作为最终结果。有人可以给我任何关于问题所在的提示吗?

class Solution:
    def countPrimeSetBits(self, L, R):
        """
        :type L: int
        :type R: int
        :rtype: int
        """
        def isPrime(num):
            if num == 0:
                return False
            list1 = list(range(num))
            list1.remove(0)
            if len(list1) != 0:
                list1.remove(num-1)
            for i in list1:
                if num % (i+1) == 0:
                    return False
                else:
                    return True

            count = 0
            for i in range(L, R+1):
                newlist = list(bin(i)[2::])
                newcount = 0
                for j in newlist:
                    if j == '1':
                        newcount += 1
                if isPrime(newcount) is True:
                    count += 1
            return count

第一个测试用例的预期结果为 23,即 L=842 和 R=888 Jupiter Notebook 按预期返回了 23,但 Leetcode 结果返回 null

最佳答案

你有两个严重的问题。第一个是所提供的代码缩进不正确,因此 countPrimeSetBits() 的代码主体是内部函数 isPrime() 的一部分。第二个问题是,除了是有史以来最糟糕的实现之外,您的 isPrime() 并没有真正起作用:

>>> isPrime(169)
True
>>> 13 * 13
169
>>> 

由于这个 else 子句将 return 放置在代码中的错误位置:

else:
    return True

下面是您的修补代码,希望在这两种环境中都能工作:

class Solution:

    def countPrimeSetBits(self, L, R):
        """
        :type L: int
        :type R: int
        :rtype: int
        """

        def isPrime(number):
            if number == 0:
                return False

            divisors = list(range(number))
            divisors.remove(0)
            if divisors:
                divisors.remove(number - 1)

            for divisor in divisors:
                if number % (divisor + 1) == 0:
                    return False

            return True

        count = 0

        for i in range(L, R + 1):
            newlist = list(bin(i)[2::])
            newcount = 0

            for j in newlist:
                if j == '1':
                    newcount += 1

            if isPrime(newcount):
                count += 1

        return count

关于python - LeetCode 762 为什么单独的代码在 Jupyter Notebook 中有效,而在 Leetcode 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54465180/

相关文章:

python - 在Python中将Dicom图像与OpenCV一起使用

python-3.x - 增加图像的宽度/高度(不调整大小)

python - 使用 np.fromfile 或 open & struct 读取 fortran 二进制文件(流式访问)

c++ - 如何在 C++ 中确定一个巨大的二进制文件的大小

python - 寻找最低未使用号码的优雅和简短(pythonic)方式

python - 我在 python 中的排序算法有时会在运行时卡住,有人可以看一下吗?

python - 我在代码底部附近收到一个列表不可调用错误,其中显示 ball.append,但我不知道如何修复它

python - 在pygame上爆炸之前给炸弹时间

python - 使用标签计数构建数据框

java - 如何在 Java 正则表达式匹配中使用 IsAlphabetic 二进制属性?