Binary Algorithms Homework
Homework Hacks and Popcorn Hacks
Popcorn Hacks
Pop Quiz 1: C
In order to effectively implement binary search algorithm, the length of the number list does not necessarily have to be even. If the number list is odd, it will still be split into two slightly uneven halves. Additionally, even if the function has duplicate values, it will not affect the midpoint calculations, thus ensuring that the binary search algorithm still works efficiently. The value of the target is also not factored into the index number, so the value of the target can be equal to -1.
This leaves us with the answer of C: the values in numList must be in sorted order. If the values are not in sorted order, the algorithm can not effectively increase or decrease its index number based on the size of the value selected; it will instead be arbitrary causing the algorithm to fail.
Pop Quiz 2: B
One disadvantage of binary search compared to linear search is that it can not be used on unsorted lists (as explained above). Option A is an advantage, rather than a disadvantage. Option C is present in both linear and binary search algorithms, which makes it neither an advantage nor a disadvantage, and finally, Option D is incorrect, as binary search will just return the first found value in the set (it does not need all unique values).
Popcorn Hack 3
def binary_search(arr, target):
left = 0
right = len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(binary_search(letters, 'c'))
2
Homework Hack
import pandas as pd
# Load the dataset
data = pd.read_csv("school_supplies.csv")
# Drop rows with missing values
data_cleaned = data.dropna()
# Sort the data by 'Price'
data_sorted = data_cleaned.sort_values(by="Price")
# Extract sorted prices as a list
price_list = data_sorted["Price"].tolist()
# Preview the sorted data
print("First few rows of sorted data:")
print(data_sorted.head())
print("Original row count:", len(data))
print("Cleaned row count:", len(data_cleaned))
# Binary search function
def binary_search(arr, target):
left = 0
right = len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
search_prices = [1.25, 6.49, 10.00]
for price in search_prices:
result = binary_search(price_list, price)
if result != -1:
print(f"Price ${price:.2f} was found at index {result} in the sorted list.")
else:
print(f"Price ${price:.2f} was NOT found in the dataset.")
First few rows of sorted data:
Product Price
5 Eraser 0.50
14 Paper Clips 0.89
2 Pencil 0.99
9 Glue Stick 1.25
1 Pen 1.50
Original row count: 15
Cleaned row count: 15
Price $1.25 was found at index 3 in the sorted list.
Price $6.49 was found at index 12 in the sorted list.
Price $10.00 was NOT found in the dataset.