Write a Python script to perform Binary search
- User
Write a Python script to perform Binary search
- Assistant
Certainly! Below is a Python script that implements binary search on a sorted list. Make sure the list you apply the search to is sorted, as binary search relies on this property to work correctly:
# Function to perform binary search def binary_search(sorted_list, target): left, right = 0, len(sorted_list) - 1 # Continue the loop until the left index is less than or equal to the right index while left <= right: # Calculate the middle index mid = (left + right) // 2 # Check if the middle element is the target if sorted_list[mid] == target: return mid # Target found, returning the index # If the target is smaller than the middle element, continue search on the left sub-array elif sorted_list[mid] > target: right = mid - 1 # If the target is greater than the middle element, continue search on the right sub-array else: left = mid + 1 # Target is not present in the list return -1 # Example sorted list and item to search for sorted_list_example = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] target_value = 7 # Perform binary search index_of_target = binary_search(sorted_list_example, target_value) # Output the result if index_of_target != -1: print(f"Target found at index {index_of_target}") else: print("Target not found in the list.") # You can also search for an item that does not exist in the list to see the function returning -1 - User
def binary_search(arr, target): low = 0 high = len(arr) - 1
while low <= high: mid = (low + high) // 2 guess = arr[mid] if guess == target: return mid if guess > target: high = mid - 1 else: low = mid + 1 return NoneExample usage:
my_list = [1, 3, 5, 7, 9] print("Index of the target is:", binary_search(my_list, 3)) # Output: Index of the target is: 1
- Assistant
Yes, the
binary_searchfunction you've provided is a correct implementation of the binary search algorithm in Python. Your example usage demonstrates searching for the number 3 in the list[1, 3, 5, 7, 9]. Since the list is already sorted, the function will work as expected and should output the index of the target (which is 1 in this case, as lists are zero-indexed in Python).The
whileloop continues to divide the search interval in half, and theifstatements determine if the target is in the left or right half of the interval, or if it equals the middle value. If the target is found, it returns the index; if the search interval is exhausted, the function returnsNoneto indicate that the target is not present in the list.Your example usage correctly calls this function and prints out the index of the target. This implementation is clean and concise while clearly illustrating binary search in action.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.