Warm tip: This article is reproduced from stackoverflow.com, please click
python python-3.x recursion search

My function for binary search returns None, I can't figure out why

发布于 2020-04-07 23:18:04

I am implementing binary search in Python, I created a function for it but somehow, I am kinda stuck in between. My funtion returns "None" as the output and I can't figure out why it is doing that. My code here:

x = [1,2,3,4,5,6,7,8,9,10]
y = 9

def bin_search(s_list, key):
    print(s_list)
    m = s_list[len(s_list)//2]
    if m == key:
        return 1
    elif m < key:
        bin_search(s_list[s_list.index(m)+1:],key)
    else:
        bin_search(s_list[0:s_list.index(m)],key)

print( bin_search(x, y)) It gives, the folowing output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[7, 8, 9, 10]
None
Questioner
Suleman Elahi
Viewed
88
John Kugelman 2020-02-01 04:17

When you make the recursive calls make sure to return the values so they're passed up the stack to the caller. Just writing bin_search(...) ignores the return value.

if m == key:
    return 1
elif m < key:
    return bin_search(s_list[s_list.index(m)+1:],key)
else:
    return bin_search(s_list[0:s_list.index(m)],key)