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