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

python why does function never reach return statement?

I always get the output None instead of False

My code:

def bi_search(elements: list, x) -> bool:
    i = len(elements)/2-1
    i = int(i)
    print(i)
    if i == 0:
        return False
    elif x == elements[i]:
        return True
    elif x < elements[i]:
        e = elements[0:i + 1]
        bi_search(e, x)
    elif x > elements[i]:
        e = elements[i+1:len(elements)]
        bi_search(e, x)

commands:

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

my_list = [1, 2, 5, 7, 8, 10, 20, 30, 41, 100]
print(bi_search(my_list, 21))

Output:

4
1
0
None

I don’t get it, it even says that is i = 0 right before the statement, so why do I not get False as a result?

>Solution :

It’s because when you fall into 3rd or 4th case and the bi_search() recursively calls itself you forgot to take into account that the call will eventually return and the flow will continue from there further. And because you miss return for these cases, python reaches ends of the function and got nothing more to do. And since caller expected the return value but received nothing, you see None.

Your code should look this way:

def bi_search(elements: list, x) -> bool:
    i = len(elements)/2-1
    i = int(i)
    print(i)
    if i == 0:
        return False
    elif x == elements[i]:
        return True
    elif x < elements[i]:
        e = elements[0:i + 1]
        return bi_search(e, x)
    elif x > elements[i]:
        e = elements[i+1:len(elements)]
        return bi_search(e, x)

and then the output is as expected:

4
1
0
False
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