-1

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))

Any help will be greatly appreciated!

Thanks!

Amanda Zhu
  • 55
  • 1
  • 10

1 Answers1

1

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)
Netwave
  • 36,219
  • 6
  • 36
  • 71
  • Apparently I was not returning anything from these two branches which was both returning None. Thanks Netwave! – Amanda Zhu Jan 16 '18 at 15:13
  • 1
    @AmandaZhu, every python function returns None by default if they don’t return anything explicitly – Netwave Jan 16 '18 at 16:58