Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why a python function still returns "None" though i am explicitly returning a value?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  if nums[mid]<target:
            return binarySearch(nums,mid+1,high,target)
        else:
            return binarySearch(nums,low,mid-1,target)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading