Popcorn Hacks
-
- C because it ensures that the binary search works because it searches based on the correct order of the list as it assumes the list is sorted. If numList is not sorted, the binary search may fail to find the correct result or even go into an incorrect path.
-
- B because binary search requires the list to be sorted or else the logic won’t work. A is wrong because Binary search is actually faster than linear search because linear goes through one element at a time which is not efficient. C is incorrect because binary search returns any occurence not just the first one. D is incorrect because binary search works with duplicates and unique values are not required
- 3.
def binary_search(lst, target):
low = 0
high = len(lst) - 1
while low <= high:
mid = (low + high) // 2
if lst[mid] == target:
return mid
elif lst[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1 # Not found
# Example usage:
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(binary_search(letters, 'c')) # Output: 2
2
Homework hack
import pandas as pd
# Step 1: Load and clean the dataset
data = pd.read_csv("school_supplies.csv")
data_cleaned = data.dropna() # Drop rows with missing data
# Step 2: Sort the data by the 'Price' column
data_sorted = data_cleaned.sort_values(by="Price")
# Step 3: Extract the sorted 'Price' column as a list
price_list = data_sorted["Price"].tolist()
# Step 4: Implement binary search
def binary_search(arr, target):
left = 0
right = len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return True
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return False
# Step 5: Search for specific prices
search_prices = [1.25, 6.49, 10.00]
for price in search_prices:
if binary_search(price_list, price):
print(f"✅ Price ${price:.2f} was found in the dataset.")
else:
print(f"❌ Price ${price:.2f} was NOT found in the dataset.")
✅ Price $1.25 was found in the dataset.
✅ Price $6.49 was found in the dataset.
❌ Price $10.00 was NOT found in the dataset.
Explanation: The code first loads the CSV file using Pandas. It then drops any rows with missing data using the dropna() method to make sure only complete entries are used. After the DataFrame is sorted by the Price column in increasing order. The sorted prices are then extracted into a Python list to help with binary search. The binary search is used to check if the specific prices exist in the sorted list of prices. The function repeatedly narrows the search range based on comparisons with the middle value of the list. Once done searching, the program prints a message indicating whether the price was found or not found in the dataset.