Search code examples
pythonpython-3.xbinaryprimes

LeetCode 762 why is separate code works in Jupiter Notebook and not in Leetcode


I am working on leetcode "762. Prime Number of Set Bits in Binary Representation" and I tested my code works fine on Jupiter Notebook and when I migrate into leetcode it shows null as a ending result. Could someone give me any hint on what the problems are?

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

The expect result is 23 for the first test case which is L=842 and R=888 Jupiter Note book gives me back 23 as expected but Leetcode returns null as a result


Solution

  • You have two serious problems. The first is that the code as presented is indented incorrectly, such that the body of code for countPrimeSetBits() is instead part of the internal function isPrime(). The second problem is that, besides being the worst implementation ever, your isPrime() doesn't really work:

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

    due to this else clause placing the return at the wrong point in the code:

    else:
        return True
    

    Below is your patched code which hopefully will work in both environments:

    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