Llama 3.3 70B × binary-search
7.3Algorithm + full docstring (Args/Returns/Raises + examples)
correctness 7.0quality 7.0documentation 8.01495ms
$ cat binary-search.prompt — what the model was asked
Implement `binary_search(arr: list[int], target: int) -> int` in Python. It should return the index of target in a sorted list, or -1 if not found. Write a proper docstring with Args, Returns, and Raises sections. Add inline comments explaining the algorithm logic. Include 3 test cases as examples in the docstring.
run 1 of 1
7.3correctness 7.0quality 7.0documentation 8.01495ms
# judge: Core binary search logic is correct, but raising ValueError for empty list deviates from the spec's expectation of returning -1, and mid-calculation doesn't address overflow-safe alternative despite rubric interest; comments are somewhat redundant but docstring and examples are otherwise complete and accurate.
$ cat llama-3.3-70b.binary-search.r1.response
```python
def binary_search(arr: list[int], target: int) -> int:
"""
This function performs a binary search on a sorted list to find the index of a target value.
Args:
arr (list[int]): A sorted list of integers.
target (int): The target value to be searched in the list.
Returns:
int: The index of the target in the list if found, -1 otherwise.
Raises:
ValueError: If the input list is empty.
Examples:
>>> binary_search([1, 2, 3, 4, 5], 3)
2
>>> binary_search([1, 2, 3, 4, 5], 6)
-1
>>> binary_search([1, 2, 3, 4, 5], 1)
0
"""
# Check if the input list is empty
if not arr:
raise ValueError("Input list is empty")
# Initialize two pointers, low and high, to the start and end of the list
low = 0 # lowest index in the current search range
high = len(arr) - 1 # highest index in the current search range
# Continue the search until the search range is not empty
while low <= high: # if low is still less than or equal to high, the search range is not empty
# Calculate the middle index of the current search range
mid = (low + high) // 2 # integer division to get the middle index
# If the target is found at the middle index, return the middle index
if arr[mid] == target:
return mid # target found, return its index
# If the target is less than the middle element, update the high pointer
elif arr[mid] > target:
high = mid - 1 # search in the left half of the current range
# If the target is greater than the middle element, update the low pointer
else:
low = mid + 1 # search in the right half of the current range
# If the target is not found after the search, return -1
return -1 # target not found
# Test cases
print(binary_search([1, 2, 3, 4, 5], 3)) # Output: 2
print(binary_search([1, 2, 3, 4, 5], 6)) # Output: -1
print(binary_search([1, 2, 3, 4, 5], 1)) # Output: 0
```
To run this code, save it to a file (e.g., `binary_search.py`) and execute it using Python (e.g., `python binary_search.py`). The test cases are included at the end of the code. You can modify the test cases to test the function with different inputs.