binary search for list in python












0














My code for binary search function in a list returns true for a value in the list, but returns None (instead of false) for values not in the list.



Can someone please explain me what I'm doing wrong?



The program is:



def searchlist(x,alist):
end=int(len(alist)-1)
mid=int(len(alist)/2)

while len(alist)>2:
if x==alist[mid] or x==alist[0] or x==alist[end] :
return("true")
break
elif x>alist[mid]:
alist=alist[mid:]
mid=int(len(alist)/2)
end=int(len(alist)-1)


elif x<alist[mid]:
alist=alist[:mid]
mid=int(len(alist)/2)
end=int(len(alist)-1)

else:
return("false")

aList=[2,3,5,7,9,12,14,23,34,45,67,89,101]

xnum=int(input("enter a number:"))
searchlist(xnum,aList)
print(searchlist(xnum,aList))









share|improve this question
























  • Without diving into the code, alist is going down to 2 values and it's ending the while loop, causing it to return None. I'd suggest print out the current state of the list each loop, and manually run through your code to figure at what point it's not working as expected. Edit: Actually, it looks like your else statement won't ever execute. Put return False after the while loop instead and it should work (I'd suggest use True and False instead of strings).
    – Peter
    Nov 19 '18 at 13:09












  • If you want to return false if you don't find what you want in your list you should put the return false after the loop, not in the loop
    – Baptiste Gavalda
    Nov 19 '18 at 13:12










  • your second elif perfomed. If you delete this block, then return ('false')
    – Rudolf Morkovskyi
    Nov 19 '18 at 13:17


















0














My code for binary search function in a list returns true for a value in the list, but returns None (instead of false) for values not in the list.



Can someone please explain me what I'm doing wrong?



The program is:



def searchlist(x,alist):
end=int(len(alist)-1)
mid=int(len(alist)/2)

while len(alist)>2:
if x==alist[mid] or x==alist[0] or x==alist[end] :
return("true")
break
elif x>alist[mid]:
alist=alist[mid:]
mid=int(len(alist)/2)
end=int(len(alist)-1)


elif x<alist[mid]:
alist=alist[:mid]
mid=int(len(alist)/2)
end=int(len(alist)-1)

else:
return("false")

aList=[2,3,5,7,9,12,14,23,34,45,67,89,101]

xnum=int(input("enter a number:"))
searchlist(xnum,aList)
print(searchlist(xnum,aList))









share|improve this question
























  • Without diving into the code, alist is going down to 2 values and it's ending the while loop, causing it to return None. I'd suggest print out the current state of the list each loop, and manually run through your code to figure at what point it's not working as expected. Edit: Actually, it looks like your else statement won't ever execute. Put return False after the while loop instead and it should work (I'd suggest use True and False instead of strings).
    – Peter
    Nov 19 '18 at 13:09












  • If you want to return false if you don't find what you want in your list you should put the return false after the loop, not in the loop
    – Baptiste Gavalda
    Nov 19 '18 at 13:12










  • your second elif perfomed. If you delete this block, then return ('false')
    – Rudolf Morkovskyi
    Nov 19 '18 at 13:17
















0












0








0







My code for binary search function in a list returns true for a value in the list, but returns None (instead of false) for values not in the list.



Can someone please explain me what I'm doing wrong?



The program is:



def searchlist(x,alist):
end=int(len(alist)-1)
mid=int(len(alist)/2)

while len(alist)>2:
if x==alist[mid] or x==alist[0] or x==alist[end] :
return("true")
break
elif x>alist[mid]:
alist=alist[mid:]
mid=int(len(alist)/2)
end=int(len(alist)-1)


elif x<alist[mid]:
alist=alist[:mid]
mid=int(len(alist)/2)
end=int(len(alist)-1)

else:
return("false")

aList=[2,3,5,7,9,12,14,23,34,45,67,89,101]

xnum=int(input("enter a number:"))
searchlist(xnum,aList)
print(searchlist(xnum,aList))









share|improve this question















My code for binary search function in a list returns true for a value in the list, but returns None (instead of false) for values not in the list.



Can someone please explain me what I'm doing wrong?



The program is:



def searchlist(x,alist):
end=int(len(alist)-1)
mid=int(len(alist)/2)

while len(alist)>2:
if x==alist[mid] or x==alist[0] or x==alist[end] :
return("true")
break
elif x>alist[mid]:
alist=alist[mid:]
mid=int(len(alist)/2)
end=int(len(alist)-1)


elif x<alist[mid]:
alist=alist[:mid]
mid=int(len(alist)/2)
end=int(len(alist)-1)

else:
return("false")

aList=[2,3,5,7,9,12,14,23,34,45,67,89,101]

xnum=int(input("enter a number:"))
searchlist(xnum,aList)
print(searchlist(xnum,aList))






python binary-search






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 19 '18 at 13:03









mkrieger1

4,30121832




4,30121832










asked Nov 19 '18 at 12:59









nikosL

62




62












  • Without diving into the code, alist is going down to 2 values and it's ending the while loop, causing it to return None. I'd suggest print out the current state of the list each loop, and manually run through your code to figure at what point it's not working as expected. Edit: Actually, it looks like your else statement won't ever execute. Put return False after the while loop instead and it should work (I'd suggest use True and False instead of strings).
    – Peter
    Nov 19 '18 at 13:09












  • If you want to return false if you don't find what you want in your list you should put the return false after the loop, not in the loop
    – Baptiste Gavalda
    Nov 19 '18 at 13:12










  • your second elif perfomed. If you delete this block, then return ('false')
    – Rudolf Morkovskyi
    Nov 19 '18 at 13:17




















  • Without diving into the code, alist is going down to 2 values and it's ending the while loop, causing it to return None. I'd suggest print out the current state of the list each loop, and manually run through your code to figure at what point it's not working as expected. Edit: Actually, it looks like your else statement won't ever execute. Put return False after the while loop instead and it should work (I'd suggest use True and False instead of strings).
    – Peter
    Nov 19 '18 at 13:09












  • If you want to return false if you don't find what you want in your list you should put the return false after the loop, not in the loop
    – Baptiste Gavalda
    Nov 19 '18 at 13:12










  • your second elif perfomed. If you delete this block, then return ('false')
    – Rudolf Morkovskyi
    Nov 19 '18 at 13:17


















Without diving into the code, alist is going down to 2 values and it's ending the while loop, causing it to return None. I'd suggest print out the current state of the list each loop, and manually run through your code to figure at what point it's not working as expected. Edit: Actually, it looks like your else statement won't ever execute. Put return False after the while loop instead and it should work (I'd suggest use True and False instead of strings).
– Peter
Nov 19 '18 at 13:09






Without diving into the code, alist is going down to 2 values and it's ending the while loop, causing it to return None. I'd suggest print out the current state of the list each loop, and manually run through your code to figure at what point it's not working as expected. Edit: Actually, it looks like your else statement won't ever execute. Put return False after the while loop instead and it should work (I'd suggest use True and False instead of strings).
– Peter
Nov 19 '18 at 13:09














If you want to return false if you don't find what you want in your list you should put the return false after the loop, not in the loop
– Baptiste Gavalda
Nov 19 '18 at 13:12




If you want to return false if you don't find what you want in your list you should put the return false after the loop, not in the loop
– Baptiste Gavalda
Nov 19 '18 at 13:12












your second elif perfomed. If you delete this block, then return ('false')
– Rudolf Morkovskyi
Nov 19 '18 at 13:17






your second elif perfomed. If you delete this block, then return ('false')
– Rudolf Morkovskyi
Nov 19 '18 at 13:17














2 Answers
2






active

oldest

votes


















1














You get None when your function does not return a value. This happens because the while loop terminates without going into the "else" branch.
A better practice would be to return True (not the string, but the Boolean value) when you find the value in the list, and return False after the loop.






share|improve this answer





























    0














    Your while loop cannot catch the else statement. you don't need that else. try this :



    def searchlist(x,alist):
    end=int(len(alist)-1)
    mid=int(len(alist)/2)
    result = False
    while len(alist)>2:
    if x==alist[mid] or x==alist[0] or x==alist[end] :
    result = True
    elif x>alist[mid]:
    alist=alist[mid:]
    mid=int(len(alist)/2)
    end=int(len(alist)-1)

    elif x<alist[mid]:
    alist=alist[:mid]
    mid=int(len(alist)/2)
    end=int(len(alist)-1)

    return result

    aList=[2,3,5,7,5,67,89,101]

    xnum=int(input("enter a number:"))
    print(searchlist(xnum,aList))





    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53375209%2fbinary-search-for-list-in-python%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      You get None when your function does not return a value. This happens because the while loop terminates without going into the "else" branch.
      A better practice would be to return True (not the string, but the Boolean value) when you find the value in the list, and return False after the loop.






      share|improve this answer


























        1














        You get None when your function does not return a value. This happens because the while loop terminates without going into the "else" branch.
        A better practice would be to return True (not the string, but the Boolean value) when you find the value in the list, and return False after the loop.






        share|improve this answer
























          1












          1








          1






          You get None when your function does not return a value. This happens because the while loop terminates without going into the "else" branch.
          A better practice would be to return True (not the string, but the Boolean value) when you find the value in the list, and return False after the loop.






          share|improve this answer












          You get None when your function does not return a value. This happens because the while loop terminates without going into the "else" branch.
          A better practice would be to return True (not the string, but the Boolean value) when you find the value in the list, and return False after the loop.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 19 '18 at 13:14









          Yakov Dan

          1,258617




          1,258617

























              0














              Your while loop cannot catch the else statement. you don't need that else. try this :



              def searchlist(x,alist):
              end=int(len(alist)-1)
              mid=int(len(alist)/2)
              result = False
              while len(alist)>2:
              if x==alist[mid] or x==alist[0] or x==alist[end] :
              result = True
              elif x>alist[mid]:
              alist=alist[mid:]
              mid=int(len(alist)/2)
              end=int(len(alist)-1)

              elif x<alist[mid]:
              alist=alist[:mid]
              mid=int(len(alist)/2)
              end=int(len(alist)-1)

              return result

              aList=[2,3,5,7,5,67,89,101]

              xnum=int(input("enter a number:"))
              print(searchlist(xnum,aList))





              share|improve this answer


























                0














                Your while loop cannot catch the else statement. you don't need that else. try this :



                def searchlist(x,alist):
                end=int(len(alist)-1)
                mid=int(len(alist)/2)
                result = False
                while len(alist)>2:
                if x==alist[mid] or x==alist[0] or x==alist[end] :
                result = True
                elif x>alist[mid]:
                alist=alist[mid:]
                mid=int(len(alist)/2)
                end=int(len(alist)-1)

                elif x<alist[mid]:
                alist=alist[:mid]
                mid=int(len(alist)/2)
                end=int(len(alist)-1)

                return result

                aList=[2,3,5,7,5,67,89,101]

                xnum=int(input("enter a number:"))
                print(searchlist(xnum,aList))





                share|improve this answer
























                  0












                  0








                  0






                  Your while loop cannot catch the else statement. you don't need that else. try this :



                  def searchlist(x,alist):
                  end=int(len(alist)-1)
                  mid=int(len(alist)/2)
                  result = False
                  while len(alist)>2:
                  if x==alist[mid] or x==alist[0] or x==alist[end] :
                  result = True
                  elif x>alist[mid]:
                  alist=alist[mid:]
                  mid=int(len(alist)/2)
                  end=int(len(alist)-1)

                  elif x<alist[mid]:
                  alist=alist[:mid]
                  mid=int(len(alist)/2)
                  end=int(len(alist)-1)

                  return result

                  aList=[2,3,5,7,5,67,89,101]

                  xnum=int(input("enter a number:"))
                  print(searchlist(xnum,aList))





                  share|improve this answer












                  Your while loop cannot catch the else statement. you don't need that else. try this :



                  def searchlist(x,alist):
                  end=int(len(alist)-1)
                  mid=int(len(alist)/2)
                  result = False
                  while len(alist)>2:
                  if x==alist[mid] or x==alist[0] or x==alist[end] :
                  result = True
                  elif x>alist[mid]:
                  alist=alist[mid:]
                  mid=int(len(alist)/2)
                  end=int(len(alist)-1)

                  elif x<alist[mid]:
                  alist=alist[:mid]
                  mid=int(len(alist)/2)
                  end=int(len(alist)-1)

                  return result

                  aList=[2,3,5,7,5,67,89,101]

                  xnum=int(input("enter a number:"))
                  print(searchlist(xnum,aList))






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 19 '18 at 13:33









                  Ali Kargar

                  1444




                  1444






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53375209%2fbinary-search-for-list-in-python%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

                      Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

                      A Topological Invariant for $pi_3(U(n))$