Home > Software engineering >  why a python function still returns "None" though i am explicitly returning a value?
why a python function still returns "None" though i am explicitly returning a value?

Time:07-29

def binarySearch(nums,low,high,target):

    if low<=high:
        mid=(low high)//2

        if nums[mid]==target:
            return mid
        if nums[mid]<target:
            binarySearch(nums,mid 1,high,target)
        else:
            binarySearch(nums,low,mid-1,target)
    else:
        return -1

def search(nums, target):
    return binarySearch(nums,0,len(nums)-1,target)
    

nums=[-1,0,3,5,9,12]
target=9

print(search(nums,target))

console output

Expected output of the above python code for binary search is '4'. But my output is 'None'. I also printed the value of mid on console output just before the line "return mid"(line number 7), it was showing the expected value '4'. But it returns 'None' instead of that expected value. Please find out the problem and it's solution.

CodePudding user response:

  if nums[mid]<target:
            return binarySearch(nums,mid 1,high,target)
        else:
            return binarySearch(nums,low,mid-1,target)
  • Related