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:

```
Your code here
```

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:

PS: if you cannot edit your post, please read around a little to increase your trust level and let you access editing your posts.

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!!! :smile:

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.
image

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!!! :smile:

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