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
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)
I would like to add to @Greg's answer, that if you want to retuen 1
to main calling function then you should return your return value
after recursion. Like:
def bin_search(s_list, key):
print(s_list)
m = s_list[len(s_list)//2]
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)
x = [1,2,3,4,5,6,7,8,9,10]
y = 7
print( bin_search(x, y))
You should also handle for the condition of no key found.
This is because your code is working as expected:
def bin_search(s_list, key):
print(s_list)
m = s_list[len(s_list)//2]
if m == key:
print('if')
return 1
elif m < key:
print('elif')
print(s_list[s_list.index(m)+1:])
bin_search(s_list[s_list.index(m)+1:],key)
else:
print('else')
print(s_list[0:s_list.index(m)])
bin_search(s_list[0:s_list.index(m)],key)
Adding in debug prints helps to pinpoint what's going on.
print( bin_search(x, y))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
elif
[7, 8, 9, 10]
[7, 8, 9, 10]
if
None
So there is actually an instance where m==key.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.