Question

Need help with Python (BinarySearch), code will be below after my statements. Thank you. Have to...

Need help with Python (BinarySearch), code will be below after my statements. Thank you.

Have to "Add a counter to report how many searches have been done for each item searched for."

Have to follow this:

1) you'll create a counter variable within the function definition, say after "the top = len(myList)-1" line and initialize it to zero.
2) Then within the while loop, say after the "middle = (bottom+top)//2" line, you'll start counting with "counter += 1" and
3) and output the value of the counter (with the print command) outside the loop and _before_ the "return found" line. It should do it.

# Binary search function in Python
# This function will look for an item in a list by dividing
# the list in half every time it searches


def binarySearch(myItem,myList):
found = False
bottom = 0
top = len(myList)-1
while bottom <= top and not found:
middle = (bottom+top) //2
if myList[middle] == myItem:
found = True
elif myList[middle] < myItem:
bottom = middle + 1
else:
top = middle - 1
return found

if __name__ == "__main__":
numberList = [1,4,6,8,12,15,18,19,24,27,31,42,43,58]
item = int(input("What number are you looking for? "))
isitFound = binarySearch(item,numberList)
if isitFound:
print("Your number is in the list!")
else:
print("Your number is not in the list!")

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the code for you:

#!/usr/bin/python
# Binary search function in Python
# This function will look for an item in a list by dividing
# the list in half every time it searches

def binarySearch(myItem,myList):
#1) you'll create a counter variable within the function definition,
#say after "the top = len(myList)-1" line and initialize it to zero.
found = False
bottom = 0
top = len(myList)-1
counter = 0
#2) Then within the while loop, say after the "middle = (bottom+top)//2" line,
#you'll start counting with "counter += 1"
while bottom <= top and not found:
middle = (bottom+top) //2
counter += 1
if myList[middle] == myItem:
found = True
elif myList[middle] < myItem:
bottom = middle + 1
else:
top = middle - 1
#3) and output the value of the counter (with the print command) outside the loop and
#_before_ the "return found" line. It should do it.
print("The number of comparisons happened is: ", counter)
return found
if __name__ == "__main__":
numberList = [1,4,6,8,12,15,18,19,24,27,31,42,43,58]
item = int(input("What number are you looking for? "))
isitFound = binarySearch(item,numberList)
if isitFound:
print("Your number is in the list!")
else:
print("Your number is not in the list!")

And the output screenshot is:

《 Terminal Shell Edit View Window Help g (D < > [N-))) 95% E a. Sat 10 Dec 01:11 ANANDA KUMAR THUMMAPUDI a E You Currently Op

Add a comment
Know the answer?
Add Answer to:
Need help with Python (BinarySearch), code will be below after my statements. Thank you. Have to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I cant get this python program to read all the unique words in a file. It...

    I cant get this python program to read all the unique words in a file. It can only read the number of the unique words in a line. import re import string from collections import Counter # opens user inputted filename ".txt" and (w+) makes new and writes def main(): textname = input("Enter the file to search: ") fh = open(textname, 'r', encoding='utf-8' ) linecount = 0 wordcount = 0 count = {} print("Sumary of the", fh) for line in...

  • Hi, I need help writing a code for this. The language is python 3, and we...

    Hi, I need help writing a code for this. The language is python 3, and we cannot use things like break, continue, exit(), lambda, map, filter, raise, try, except, and assert in our code. Thank you! We must write a function called "binary_to_decimal(binary_number)" that takes a string for a binary number and output the decimal integer for that number. The solution, aka the code, MUST contain a for loop of this form (power is an integer variable you define earlier):...

  • python programming: Can you please add comments to describe in detail what the following code does:...

    python programming: Can you please add comments to describe in detail what the following code does: import os,sys,time sl = [] try:    f = open("shopping2.txt","r")    for line in f:        sl.append(line.strip())    f.close() except:    pass def mainScreen():    os.system('cls') # for linux 'clear'    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print(" SHOPPING LIST ")    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print("\n\nYour list contains",len(sl),"items.\n")    print("Please choose from the following options:\n")    print("(a)dd to the list")    print("(d)elete from the list")    print("(v)iew the...

  • I need help with my python class. thanks! Question 12 Code Example 4-4 main program: import...

    I need help with my python class. thanks! Question 12 Code Example 4-4 main program: import arithmetic as a def multiply(num1, num2):     product = num1 * num2     result = a.add(product, product)     return result     def main():     num1 = 4     num2 = 3     answer = multiply(num1, num2)     print("The answer is", answer) if __name__ == "__main__":     main() arithmetic module: def add(x, y):     z = x + y     return z Refer to Code...

  • Could anyone help add to my python code? I now need to calculate the mean and...

    Could anyone help add to my python code? I now need to calculate the mean and median. In this programming assignment you are to extend the program you wrote for Number Stats to determine the median and mode of the numbers read from the file. You are to create a program called numstat2.py that reads a series of integer numbers from a file and determines and displays the following: The name of the file. The sum of the numbers. The...

  • [Using Python] I need my code given below to loop the user input, so that you...

    [Using Python] I need my code given below to loop the user input, so that you are asked to input without it stopping after 4 inputs. Code: #A program that converts a hexadecimal number to its decimal value #Define function for hexadecimal to decimal def hexToDec(hexi): result = 0 #For loop to test input for correct values for char in hexi: if 'A' <= char <= 'F' or 'a' <= char <= 'f': if 'a' <= char <= 'f': result...

  • I need help with the adding the following to my python code (also provided below) M5A6Part2...

    I need help with the adding the following to my python code (also provided below) M5A6Part2 ⦁   When a user successfully votes, add the user’s voterID to the _voterIDsVoted list ⦁   When a user successfully votes, increment the value of the variable that counts the votes for the candidate the user voted for. This would be either _candidateAVotes or _candidateBVotes Hint: run your original test code again. If you reused a valid voter ID in your tests it should cause...

  • Hello I need help with python programming here is my code # Trivia Challenge # Trivia...

    Hello I need help with python programming here is my code # Trivia Challenge # Trivia game that reads a plain text file import sys def open_file(file_name, mode): """Open a file.""" try: the_file = open(file_name, mode) except IOError as e: print("Unable to open the file", file_name, "Ending program.\n", e) input("\n\nPress the enter key to exit.") sys.exit() else: return the_file def next_line(the_file): """Return next line from the trivia file, formatted.""" line = the_file.readline() line = line.replace("/", "\n") return line def next_block(the_file):...

  • Python help! Any help is appreciated, thank you! Fill in the missing function, monthString(), in the...

    Python help! Any help is appreciated, thank you! Fill in the missing function, monthString(), in the program. The function should take number between 1 and 12 as a parameter and returns the corresponding month as a string. For example, if the parameter is 1, your function should return "January". If the parameter is 2, your function should return out "February", etc. def monthString(monthNum): """ Takes as input a number, monthNum, and returns the corresponding month name as a string. Example:...

  • PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment...

    PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment the lines please so I can understand. There are short and med files lengths for each the list of names/ids and then search id file. These are the input files: https://codeshare.io/aVQd46 https://codeshare.io/5M3XnR https://codeshare.io/2W684E https://codeshare.io/5RJwZ4 LinkedList ADT to store student records(code is below). Using LinkedList ADT instead of the Python List. You will need to use the Student ADT(code is below) Imports the Student class...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT