# Python Code for binary search in a List

``````def bin_search(a,m):
start=0
end=len(a)-1
if(end==start):
if(a[end]==m):
return 1
else:
return 0
if(end-start==1):
if(a[end]==m) or (a[start]==m):
return 1
else:
return 0
if(end-start>1):
mid=(end+start)//2
if(a[mid]==m):
return 1
if(a[mid]>m):
a=a[start:mid-1]
return bin_search(a,m)
if(a[mid]<m):
a=a[mid+1:end]
return bin_search(a,m)
else:
return 0
l=list(range(100))
``````

THIS WORKS FOR CERTAIN NUMBER BUT NOT FOR OTHERS,CAN SOMEONE TELL WHATS WRONG?

Hello @LokiLeto! Please edit your postâ€™s code to be formatted like this:

`````````
```
``````

So that it is easier for staff and members of the community to help you with your issue!

Also see this guide on how to share your code:

2 Likes

sorry didnt know this,Im not able to edit my post Will do it like this next time!

Can you either provide the link to your Repl or make a new post with the formatted code? There are a lot of `if` statements there and I want to make sure Iâ€™m using the right indentations when troubleshooting this code.

https://replit.com/@LokiLeto/fook#main%20(copy).py
This is the link to the repl.Hope this helps!!!

for binary search, the list needs to be sorted. Also, use bisect as itâ€™s faster and also builtin and easier. If this answer helped you please mark as solved

Why does the function do this? Iâ€™d think it would reach the recursion limit.

no i dont think it will hit recursion limit its halving so ig it wont

the list is sorted list of 100 nosâ€¦thanks i will check bisect!!!

1 Like

I am assuming this is a school assignment, so BISECT is not an option and giving you the code either.

Your code is just too complex and trying too many checks. the basic idea of binary search is take the middle of a list. If this is the searched element return 1, otherwise search in the half of the list where the number could be recursively. You just need to extract min and max (tail and head) values and check if the list is composed by two elements.

you will not hit a recursion limit

2 Likes

yeah thats the logic I used,but still some elements its turning out false and i dont think its because of recursion limit becaus recursion error aint throwing up.

It is because your code is too complex, too many IFs â€¦ and makes errors. Start from simplifying the code â€¦

1 Like