Python return None instead of value

Question:

I am trying to implement a very easy Binary search question here: return the index of an array that is plus/minus one from the given target.

However, when I execute this code, my result is always None. Python does not seem to capture my return value.

Here’s my code:

class Solution:
    def closestNumber(self, A, target):
        if len(A) == None:
            return -1

        if target - 1 > A[-1] or target + 1 < A[0]:
            return -1

        result = self.BinarySearch(0,len(A), A, target)
        return result
    
    def BinarySearch(self,startIndex, endIndex, A, target):
        if startIndex > endIndex:
            return -1
            
        mid = (startIndex + endIndex)//2
        print(mid)
        if target == A[mid]:
            return mid
        
        if target + 1 == A[mid] or target - 1 == A[mid]:
            return mid
            
        if target + 1 > A[mid]:
            self.BinarySearch(mid, endIndex, A, target)

        if target - 1 < A[mid]:
            self.BinarySearch(startIndex, mid, A, target)
            

    print(Solution().closestNumber([1,4,6,10,20],21))
Asked By: Amanda Zhu

||

Answers:

You lack 2 return statements in the recursive call branches of your code:

if target + 1 > A[mid]:
    return self.BinarySearch(mid, endIndex, A, target)

if target - 1 < A[mid]:
    return self.BinarySearch(startIndex, mid, A, target)
Answered By: Netwave
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.