Here is the code, I am trying to get a binary search result using a method inside the class. The class has more functions but only this function is giving the wrong output (None
in place an integer). The if
part from line number 10 to 15 is causing the problem.
class Solution:
def getNum(self, nums, x):
L_nums = len(nums)
j = self.binary_search( nums, 0, L_nums-1, x)
print("j=",j)
def binary_search(self, nums, start, end, x):
print("BS called start=>", start,"end=>", end,"x=>", x)
if end==start:
if nums[end]==x:
return end
else:
print("called else and returing -1")
return -1
i = (end-start)//2 + start
print("i=",i)
if x==nums[i]:
return i
elif x>nums[i]:
self.binary_search(nums, i+1, end, x)
else:
self.binary_search(nums, start, i-1, x)
sol = Solution()
sol.getNum([1,3,5,7,9],1)
output: here j
should be 0, in place of that it is returning None
BS called start=> 0 end=> 4 x=> 1
i= 2
BS called start=> 0 end=> 1 x=> 1
i= 0
j= None