#๐Ÿ”’ How is this binary search code not working??

74 messages ยท Page 1 of 1 (latest)

final jungle
#

Code:


n=int(input("Enter the size of ur list: "))
lis1=[]
for i in range(n):
    ele=int(input(f"Enter element {i+1}: "))
    lis1.append(ele)
print(f"Your list is: \n{lis1}")
key=int(input("Enter the element you wish to find: "))
def sort_list(lis):
    sorted_list=[]
    while lis:
        small_num=min(lis)
        sorted_list.append(small_num)
        lis.remove(small_num)
    print(sorted_list)
    return sorted_list
sorted_list=sort_list(lis1)
def binary_search(upper,lower=0):
    result=None
    while lower<=upper:
        mid=(lower+upper)//2
        if sorted_list[mid]==key:
            result=mid
        elif sorted_list[mid]<key:
            binary_search(upper,mid+1)
        else:
            binary_search(mid-1)
    return result
if binary_search(n-1)==None:
    print("Your no is not present in the list!")
else:
    print(f"{key} was found at position {result}!")
empty sequoiaBOT
#

@final jungle

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

final jungle
#

Gets stuck here

minor galleon
#

Explain what this code should do

final jungle
#

binary search

#

algorithm

#

should tell if the element is there in the list and if yes, which pos

#

if not then print the respective statement

minor galleon
#

Ok

final jungle
#

Its a really famous algorhithm u can look it up

#

I just dont get why my code would not work, + its not an error it just.. gets stuck

minor galleon
#

First instead of sorlist function u created u can simply type

Lis1.sort()

This will sort out your list in ascending order

final jungle
#

Ohk

#

But sort list function works fine

minor galleon
#

It make your code lenthy and hard to understand

sacred night
#

u defined the binary_search function with 2 parameters yet u are only giving it 1 argument

minor galleon
#

Instead of writing 10 lines u can do the same thing in one line

final jungle
final jungle
final jungle
#

only to the upper arguement

minor galleon
final jungle
#

we now get an error @minor galleon

#

why is mid nonetype tho

#

both lower and upper are integers

#

and //2 should also result in integer

minor galleon
#
If key in lis1:
      Print(f'The key is at index : {lis1.index(key)}')
Else:
       Print("your key is not present in the list")
#

Instead of binarysearch write this

modest smelt
final jungle
#

That defeats the whole purpose

modest smelt
final jungle
#

Thats LINEAR SEARCH

final jungle
#

Wait wut

#

how

#

Wait thats cus of the correction @minor galleon suggested

modest smelt
#

!e

my_list = [1, 3, 2]
other = my_list.copy()
print(my_list.sort()) # returns None
print(my_list) # is sorted
print(sorted(other)) # sorted list
print(other) # but isn't saved to the list```
empty sequoiaBOT
final jungle
#

sort function sorts lis1 but returns none in sorted_list

lone rover
#

i don't think binary searches are supposed to recurse...
also, when you're recursing, you're not doing anything with the return value anyway

final jungle
#

But now there is this error

#

No error it just gets stuck

modest smelt
#

You want to set result to whatever the recursed function returns

final jungle
lone rover
final jungle
#

so this is inefficient than iterative one

#

Also i found a code online

minor galleon
final jungle
#
if arr[mid] == x:
            return mid

        # If element is smaller than mid, then it
        # can only be present in left subarray
        elif arr[mid] > x:
            return binarySearch(arr, low, mid-1, x)

        # Else the element can only be present
        # in right subarray
        else:
            return binarySearch(arr, mid + 1, high, x)
final jungle
#

In the if-else cases as well

final jungle
#

Nah nvm its still the same

lone rover
final jungle
#

For anyone new on this thread the current code is:

n=int(input("Enter the size of ur list: "))
lis1=[]
for i in range(n):
    ele=int(input(f"Enter element {i+1}: "))
    lis1.append(ele)
print(f"Your list is: \n{lis1}")
key=int(input("Enter the element you wish to find: "))
lis1.sort()
def binary_search(list,upper,lower=0):
    result=None
    while lower<=upper:
        mid=(lower+upper)//2
        if lis1[mid]==key:
            result=mid
        elif lis1[mid]<key:
            return binary_search(list,upper,mid+1)
        elif lis1[mid]>key:
            return binary_search(list,mid-1)
    return result
output=binary_search(lis1,n-1)
if output==None:
    print("Your no is not present in the list!")
else:
    print(f"{key} was found at position {result}!")
final jungle
#

I never liked recrusion

#

Guys i made it work!

#

Code:

n=int(input("Enter the size of ur list: "))
lis1=[]
for i in range(n):
    ele=int(input(f"Enter element {i+1}: "))
    lis1.append(ele)
print(f"Your list is: \n{lis1}")
key=int(input("Enter the element you wish to find: "))
lis1.sort()
def binary_search(list,upper,lower=0):
    result=None
    if lower<=upper:
        mid=(lower+upper)//2
        if lis1[mid]==key:
            result=mid
            return result
        elif lis1[mid]<key:
            return binary_search(list,upper,mid+1)
        elif lis1[mid]>key:
            return binary_search(list,mid-1)
    else:
        return result
output=binary_search(lis1,n-1,0)
if output==None:
    print("Your no is not present in the list!")
else:
    print(f"{key} was found at position {output+1}!")
#

Thanks all for ur help

lone rover
#

recursion can make some things cleaner or more concise at the cost of performance, i tend to avoid it on principle though - you can implement your own recursion stack with a list and a while loop, even

final jungle
#

i had to use if and not while upper>lower

final jungle
final jungle
#

K thx

#

!close

empty sequoiaBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.