This is new code based on some new ideas to reduce calls to is_bad_version
. Refer to the previous version of the code discussion from here.
Any smarter ideas for better time complexity, any code bug or code style advice are highly appreciated. My major idea is divide and conquer like a binary search/quick select.
Problem:
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
Source code:
def is_bad_version(number):
if number == 0:
return False
else:
return True
def find_first_bad_index(numbers):
start = 0
end = len(numbers) - 1
if start == end:
if is_bad_version(numbers[start]):
return start
else:
raise Exception('all good!')
while start < end:
mid = start + (end - start) / 2
if is_bad_version(numbers[mid]):
end = mid
else:
start = mid + 1
if start == end:
if is_bad_version(numbers[start]):
return start
else:
raise Exception('all good!')
if __name__ == "__main__":
print find_first_bad_index([0,0,0,1,1,1,1,1])
print find_first_bad_index([0,0,0,0,0,0,0,1])
raise Exception('all good!')
, what an interesting exception. lol. \$\endgroup\$bisect
? Alsois_bad_version
could justreturn number
, as0
is false-y and1
is truth-y. \$\endgroup\$bisect(sequence, x, lo=0, hi=len(a))
had akey
likesorted(iterable[, key][, reverse])
? \$\endgroup\$an inefficient design
is a strong statement. (Think of python supporting memoisation per decorator.) \$\endgroup\$