-1
\$\begingroup\$

I am a python beginner and I wrote a program that compares between the binary search method for finding a number and the linear one. However, when I run it It does not function properly and would stop when I enter an input and print nothing. Please, may someone explain what is wrong with it? THANK YOU SO MUCH

import random
import time


n=1000000


start = time.time()
lst=[random.randint(0,100*n) for i in range(n)]
start=time.time()
def linear():

 for c in lst:
    if c==e:
        return "found"
    else:
        return "not found"
end = time.time() # record end time
print('time to sort:', (end-start)/100, 'seconds')
print(linear())



lst=[random.randint(0,100*n) for i in range(n)]
start=time.time()
def binary(e,lst):


 Ubound=len(lst)-1
 Lbound=0
 mid=(Ubound+Lbound)//2
 found=True
 lst.sort()

 while found and Lbound<=Ubound:
      if e==lst[mid] :
         found=True
         return found
      elif lst[mid]<e:
          Lbound=mid+1
      else:
          Ubound=mid-1
 return found  
end=time.time()
print('time to sort:', (end-start)/100, 'seconds')

e=int(input("what are you looking for?"))
if binary(e,lst):`enter code here`
    print("item has been found")
else:
    print("item has not been found")
\$\endgroup\$
2
  • \$\begingroup\$ This question would be better served on Stack Overflow \$\endgroup\$
    – Cubemaster
    Commented Nov 1, 2018 at 20:40
  • \$\begingroup\$ This will get much more attention on Stack Overflow, Code Review is primarily for optimizing already working code \$\endgroup\$
    – Cubemaster
    Commented Nov 1, 2018 at 21:03

1 Answer 1

0
\$\begingroup\$

Take a look at this portion of your code:

found=True
 lst.sort()

 while found and Lbound<=Ubound:

You set found to true before checking if it exists. Here you should set it to false before you run the loop.

Also, please keep in mind, as mentioned in the comments to your question, that questions regarding logic and algorithms are better suited for StackOverflow, CodeReview is for already working code, to either further optimize it or improve it. Please be careful of that in the future.

Hope that answers your question!

\$\endgroup\$
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.