Hey Im a first year CS student and I’m trying to finish some homework on Zybooks but the code I written keeps failing. Is there any advice/feedback someone can give me. Thank you
the Zybook problem
my output
this is the code is used
calls = 0
comparisons = 0
def binary_search(nums, target, low, high):
global calls, comparisons
calls += 1
if calls > 4 or comparisons > 7:
return -1
if high >= low:
mid = (high + low) // 2
comparisons += 1
if nums[mid] == target:
return mid
elif nums[mid] > target:
comparisons += 1
return binary_search(nums, target, low, mid - 1)
else:
comparisons += 1
return binary_search(nums, target, mid + 1, high)
else:
return -1
nums = list(map(int,input().split()))
target = int(input())
result = binary_search(nums, target, 0, len(nums) - 1)
print(f'index: {result}, recursions: {calls}, comparisons: {comparisons}')
New contributor
Darth L Jackson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.