Skip to content

Instantly share code, notes, and snippets.

@Tr-reny
Last active February 12, 2023 10:14
Show Gist options
  • Save Tr-reny/5b55cc731ee1f74f0a6a2b0abd794020 to your computer and use it in GitHub Desktop.
Save Tr-reny/5b55cc731ee1f74f0a6a2b0abd794020 to your computer and use it in GitHub Desktop.
This is a Intern Developer Assistant Python interview question to of implementation of a binary search algorithm to find the first number of teaspoons of sugar that makes a cake too sweet.the binary_search t will then takes two inputs, n (the number of teaspoons of sugar required by the recipe) and isTooSweet (a function that returns True if the…
# This code implements a binary search algorithm to find the first number of teaspoons of sugar that makes a cake too sweet
def binary_search(n, isTooSweet):
# Set left as lower bound, right as upper bound
left = 1
right = n
# repeat until right - left <= 1
while right - left > 1:
# find average of left and right
mid = (left + right) // 2
# check if isTooSweet(mid) is true, and find balance
if isTooSweet(mid):
right = mid
else:
left = mid
return right
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment