Last active
February 12, 2023 09:32
-
-
Save Tr-reny/863691239dbc9d371edfec0a2d49b1ca 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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, then adjust the bonds | |
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