Problem 1

# list indexing and list procedures

food = ['aapple','bapple','capple','orange','tofu','meatballs','fishballs','amongus','trees','kim jong un']
def foodCheck(): # define function to check the list, prints size and elements
    l = len(food) # the size of the food array
    print(f"right now there are {l} foods")
    print("this is the list")
    print(food) # print list
foodCheck() # call function to check on list
food.remove(food[-1]) # remove last element
foodCheck()
food = [i for i in food if i[-5:] != 'apple'] # uses list comprehension. removes all elements in list that ends with 'apple'
foodCheck()
print("My favorite foods are among the ones with 'b' in them:")
for i in food: # loops through all elements of list
    if 'b' in i: # if letter 'b' is in the element, it is favorite food
        print(i)
right now there are 10 foods
this is the list
['aapple', 'bapple', 'capple', 'orange', 'tofu', 'meatballs', 'fishballs', 'amongus', 'trees', 'kim jong un']
right now there are 9 foods
this is the list
['aapple', 'bapple', 'capple', 'orange', 'tofu', 'meatballs', 'fishballs', 'amongus', 'trees']
right now there are 6 foods
this is the list
['orange', 'tofu', 'meatballs', 'fishballs', 'amongus', 'trees']
My favorite foods are among the ones with 'b' in them:
meatballs
fishballs

Problem 2

# determine the worst case number of iterations of a binary search for an array of length 20
import math
print(int(math.log2(20) // 1)+1) # the best solution
# take log base 2 of the array size and round up (or +1)

# the slow way
arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
def binary_search(arr,target,i): # binary search it
    l = 0
    r = 19
    while l <= r:
        mid = (l+r)//2
        i += 1
        
        if arr[mid] == target:
            return i # the binary search should return how many iterations it took
        elif arr[mid] < target:
            l = mid + 1
        elif arr[mid] > target:
            r = mid - 1
max_iter = 0 # initiate maximum amount of iterations
for t in range(19):
    iter = binary_search(arr,t,0) # binary search all the items
    max_iter = max(iter,max_iter) # change max_iter if new max is found
print(f"After actually binary searching: {max_iter}")
5
After actually binary searching: 5

Problem 3

This code loops over all the elements of myList and multiplies everything by 2. So the final output should be A) [20, 40, 60, 80, 100].