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:
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?
CodePudding user response:
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 jumps out of the elif
and reaches ends of the function. As there's no more code in the function to execute, Python exits that function and returns execution to caller, but as caller expected to get something back (the return value) from the function it called we got a problem. Python solves this problem it goes with use of None
to still return something it does not have really and also to indicate that it had nothing better to give back.
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
CodePudding user response:
You don't have return statements in the last 2 elif
, you want to return the value of recursive call
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)