9. def binary_search(item, lst): 10 11 Function binary_search -- 12 Perform a binary search for a given item. Return True when a matching item is found. Return False if no match is found. 13 14...


Here is the iterative implementation of binary search:




For each call to binary_search below, indicate how many times the code inside the while loop will execute.


animals = ["aardvark", "cat", "dog", "elephant", "panda"]





1. binary_search("elephant", animals)








2. binary_search("dog", animals)








3. binary_search("anteater", animals)



9.<br>def binary_search(item, lst):<br>10<br>11<br>Function<br>binary_search<br>--<br>12<br>Perform a binary search for a given item. Return True when a<br>matching item is found. Return False if no match is found.<br>13<br>14<br>Parameters:<br>15<br>item<br>the item to search for.<br>--<br>16<br>lst<br>the list to search in.<br>--<br>17<br>18<br>left_index<br>= 0<br>right_index<br>found = False<br>19<br>len (lst) - 1<br>%3D<br>20<br>21<br>right_index and not found:<br>(left_index + right_index) // 2<br>22<br>while left_index <=<br>23<br>middle<br>if lst[middle]<br>found = True<br>24<br>item:<br>25<br>26<br>elif item < lst[middle]:<br>27<br># Search left<br>28<br>right_index<br>middle - 1<br>29<br>else:<br>30<br># Search right<br>31<br>left_index<br>= middle + 1<br>32<br>return found<br>

Extracted text: 9. def binary_search(item, lst): 10 11 Function binary_search -- 12 Perform a binary search for a given item. Return True when a matching item is found. Return False if no match is found. 13 14 Parameters: 15 item the item to search for. -- 16 lst the list to search in. -- 17 18 left_index = 0 right_index found = False 19 len (lst) - 1 %3D 20 21 right_index and not found: (left_index + right_index) // 2 22 while left_index <= 23="" middle="" if="" lst[middle]="" found="True" 24="" item:="" 25="" 26="" elif="" item="">< lst[middle]:="" 27="" #="" search="" left="" 28="" right_index="" middle="" -="" 1="" 29="" else:="" 30="" #="" search="" right="" 31="" left_index="middle" +="" 1="" 32="" return="">

Jun 08, 2022
SOLUTION.PDF

Get Answer To This Question

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here