Question

I want to replace true with the number of comparisons that were made. For example, if...

I want to replace true with the number of comparisons that were made. For example, if I have a list of [1,4,5,6,7,8] and I ask the program to find 6. is it possible to tell me how many comparisons it took to find 6?  PYTHON

here is my code:

def linear_search(vals,target):

    for val in vals:

        if val == target:

            return True

    return -1

def binary_search(vals,target):

    lo = 0

    hi = len(vals)-1

    mid(lo+hi)//2

    while lo <= hi and vals [mid]!=target:

        if target > vals[mid]:

            lo = mid+1

        else:

            hi = mid-1

        mid = (lo+hi)//2

    if vals[mid] == target:

        return True

    else:

        return -1

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


ANSWER:-

CODE:-

def linear_search(vals,target):

    noOfComparisons = 0

    for val in vals:

        noOfComparisons += 1

        if val == target:

            return noOfComparisons

    return -1

def binary_search(vals,target):

    noOfComparisons = 0

    lo = 0

    hi = len(vals)-1

    mid = (lo+hi)//2

    while lo <= hi and vals [mid]!=target:

        noOfComparisons += 1

        if target > vals[mid]:

            lo = mid+1

        else:

            hi = mid-1

        mid = (lo+hi)//2

    if vals[mid] == target:

        noOfComparisons += 1

        return noOfComparisons

    else:

        return -1

lst = [1,4,5,6,7,8]
print("List:",lst)
print("No of comparisons to find 6 using linear search:",linear_search(lst,6))
print("No of comparisons to find 6 using binary search:",binary_search(lst,6))

NOTE:- If you need any modifications in the code,please comment below.Please give positive rating.THUMBS UP.

             THANK YOU!!!!

OUTPUT:-

CODE SCREENSHOT:-

Add a comment
Know the answer?
Add Answer to:
I want to replace true with the number of comparisons that were made. For example, if...
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
  • (Please help me with Coding in Python3) AVLTree complete the following implementation of the balanced (AVL)...

    (Please help me with Coding in Python3) AVLTree complete the following implementation of the balanced (AVL) binary search tree. Note that you should not be implementing the map-based API described in the plain (unbalanced) BSTree notebook — i.e., nodes in the AVLTree will only contain a single value. class AVLTree: class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def rotate_right(self): n = self.left self.val, n.val = n.val, self.val self.left, n.left, self.right, n.right...

  • Python, I need help with glob. I have a lot of data text files and want...

    Python, I need help with glob. I have a lot of data text files and want to order them. However glob makes it in the wrong order. Have: data00120.txt data00022.txt data00045.txt etc Want: data00000.txt data00001.txt data00002.txt etc Code piece: def last_9chars(x):     return(x[-9:]) files = sorted(glob.glob('data*.txt'),key = last_9chars) whole code: import numpy as np import matplotlib.pyplot as plt import glob import sys import re from prettytable import PrettyTable def last_9chars(x):     return(x[-9:]) files = sorted(glob.glob('data*.txt'),key = last_9chars) x = PrettyTable() x.field_names =...

  • Page 3 of 7 (Python) For each substring in the input string t that matches the...

    Page 3 of 7 (Python) For each substring in the input string t that matches the regular expression r, the method call re. aub (r, o, t) substitutes the matching substring with the string a. Wwhat is the output? import re print (re.aub (r"l+\d+ " , "$, "be+345jk3726-45+9xyz")) a. "be$jk3726-455xyz" c. "bejkxyz" 9. b. "be$jks-$$xyz" d. $$$" A object a- A (2) 10. (Python) What is the output? # Source code file: A.py class A init (self, the x): self.x-...

  • Need help the first picture is the code I have so far the second are the...

    Need help the first picture is the code I have so far the second are the requirements. It’s a deque array in python class dequeArray: DEFAULT-CAPACITY 10 #moderate capacity for all new queues def init (self): self.capacity-5 capacity self.capacity self.data self, make array(self. capacity) self. size self. front-θ def len (self): return self. size def _getiten-(self, k); #Return element at index k if not θ k < self. size: raise IndexError('invalid index) return self._data[k] def isEmpty(self): if self. data0: return...

  • PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please...

    PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please so I can understand LinkedList ADT: class myLinkedList:     def __init__(self):         self.__head = None         self.__tail = None         self.__size = 0     def insert(self, i, data):         if self.isEmpty():             self.__head = listNode(data)             self.__tail = self.__head         elif i <= 0:             self.__head = listNode(data, self.__head)         elif i >= self.__size:             self.__tail.setNext(listNode(data))             self.__tail = self.__tail.getNext()         else:             current = self.__getIthNode(i - 1)             current.setNext(listNode(data,...

  • 1. Create a Python script file called Assignment_Ch06-02_yourLastName.py. (Replace yourLastName with your last name.) 2. Write...

    1. Create a Python script file called Assignment_Ch06-02_yourLastName.py. (Replace yourLastName with your last name.) 2. Write a Python program that prompts the user for a sentence, then replaces all the vowels in the sentence with an asterisk: '*' Your program should use/call your isVowel function from Assignment_Ch06-01. You can put the isVowel() function in a separate .py file, without the rest of the Ch06-01 code, and then import it. 6-01 CODE: def isVowel(x):     if x in "aeiouyAEIOUY":         return True     else:...

  • Please, I need help debuuging my code. Sample output is below MINN = 1 MAXX =...

    Please, I need help debuuging my code. Sample output is below MINN = 1 MAXX = 100 #gets an integer def getValidInt(MINN, MAXX):     message = "Enter an integer between" + str(MINN) + "and" + str(MAXX)+ "(inclusive): "#message to ask the user     num = int(input(message))     while num < MINN or num > MAXX:         print("Invalid choice!")         num = int(input(message))     #return result     return num #counts dupes def twoInARow(numbers):     ans = "No duplicates next to each...

  • 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...

  • COMPLETE THE _CONSTRUCT() AND CONSTRUCTTREE() FUNCTIONS class expressionTree:    class treeNode: def __init__(self, value, lchild, rchild):...

    COMPLETE THE _CONSTRUCT() AND CONSTRUCTTREE() FUNCTIONS class expressionTree:    class treeNode: def __init__(self, value, lchild, rchild): self.value, self.lchild, self.rchild = value, lchild, rchild def __init__(self): self.treeRoot = None    #utility functions for constructTree def mask(self, s): nestLevel = 0 masked = list(s) for i in range(len(s)): if s[i]==")": nestLevel -=1 elif s[i]=="(": nestLevel += 1 if nestLevel>0 and not (s[i]=="(" and nestLevel==1): masked[i]=" " return "".join(masked) def isNumber(self, expr): mys=s.strip() if len(mys)==0 or not isinstance(mys, str): print("type mismatch error: isNumber")...

  • What is the role of polymorphism? Question options: Polymorphism allows a programmer to manipulate objects that...

    What is the role of polymorphism? Question options: Polymorphism allows a programmer to manipulate objects that share a set of tasks, even though the tasks are executed in different ways. Polymorphism allows a programmer to use a subclass object in place of a superclass object. Polymorphism allows a subclass to override a superclass method by providing a completely new implementation. Polymorphism allows a subclass to extend a superclass method by performing the superclass task plus some additional work. Assume that...

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
ADVERTISEMENT