import random
def turn():
max_int = 0
for i in range(4):
nint = random.randint(1, 10)
if nint > max_int:
max_int = nint
print(max_int)
turn()
turn()
Question 4 / 5
Explanation:
To search for element 69, you would first look at the middle index, 5 (4.5, round up to 5). This is 6. As six is less than 69, you would look at the greater than half. This half's middle index is 7 (5+9 = 14/2 = 7). the seventh index is 11, which is less than 69. Then we look at the 8th index ((8+8)/2 = 8). Since 8 = 69, we have searched and found the correct number.
Question 8
Binary search is far quicker than sequential search because binary search inherently rules out half of the possibilities every iteration. Since you start at the middle index, you can either choose to pick the group that is greater than the middle index, or the group that is lower. As a result, you will rule out half of the known possibilities every single time you make a cut.
Question 9
Out of the list [64,36,16,11,9]
, I would be searching for 36. First I would select the middle element ((1+5)/2 = 3, and for the purpose of collegeboard that is the middle element), and 16 is less than 36, so I would move back, (as the list is reversed). Hence, I would select the 2nd element ((1+3)/2 = 2) and that is equal to 36, so it would take me two tries in order to get to 36.
from PIL import Image
im = Image.open("../images/Tree2.png")
display
lst = [1,2,3,4,5,6]
lst.reverse()
def binarySearch(lst, toFind):
min = 0 # Min index, set to first to survey whole list
max = len(lst)-1 # Max index, set to last to survey whole list
reversed = False
if lst[min] > lst[max]:
lst.reverse()
reversed = True # sets so we can assure no side affects
print("reversed")
# we only really want the list to be in ascending order, so we reverse it if it isn't
while True:
ind = int(round((min+max)/2)) # find middle index
mid = lst[ind] # set middle index to variable
print(mid)
if mid == toFind: # if it is equal, we're done
if reversed:
lst.reverse()
return
else: # otherwise
if mid < toFind: # if it is less than the answer is above as a result the min value moves up
min = ind
else: # otherwise if it is greater the answer is under and therefore max moves down
max = ind
print("trying search with lst searching for 5")
binarySearch(lst, 5)
print("trying search with lst searching for 1")
binarySearch(lst, 1)