-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\$

closed as off-topic by Sᴀᴍ Onᴇᴌᴀ, 200_success, chux, Heslacher, t3chb0t Nov 2 '18 at 7:30

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Code not implemented or not working as intended: Code Review is a community where programmers peer-review your working code to address issues such as security, maintainability, performance, and scalability. We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review." – Sᴀᴍ Onᴇᴌᴀ, 200_success, chux, Heslacher, t3chb0t
If this question can be reworded to fit the rules in the help center, please edit the question.

  • \$\begingroup\$ This question would be better served on Stack Overflow \$\endgroup\$ – Cubemaster Nov 1 '18 at 20:40
  • \$\begingroup\$ This will get much more attention on Stack Overflow, Code Review is primarily for optimizing already working code \$\endgroup\$ – Cubemaster Nov 1 '18 at 21:03
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\$

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