2
\$\begingroup\$

Working on below find first bad version problem, post my code in Python 2.7, 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.

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 isBadVersion(number):
    if number == 0:
        return False
    else:
        return True
# 0 means good, 1 means bad
def find_first_bad_index(numbers):
    start = 0
    end = len(numbers)-1
    if isBadVersion(numbers[start]) == True:
        return start
    if isBadVersion(numbers[end]) == False:
        raise Exception('all good')
    while start <= end:
        mid = start + (end-start)/2
        if isBadVersion(numbers[mid]) == True:
            if start == end:
                return end
            else:
                end = mid
        else:
            start = mid + 1

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])
\$\endgroup\$
  • 5
    \$\begingroup\$ You already have been redirected to PEP8 in various answers to your previous questions. Why is it that we still see camelCased function names and lack of whitespace all around your codes? \$\endgroup\$ – 409_Conflict Dec 15 '16 at 9:23
  • \$\begingroup\$ @MathiasEttinger, thanks. Today I figured out how to config it in Pycharm for automatic check. \$\endgroup\$ – Lin Ma Dec 18 '16 at 0:50
5
\$\begingroup\$

Obligatory PEP 8 reminder:

  • Whitespace is important.
  • Whitespace is important too.
  • Recommendations state that you should:

    • Design exception hierarchies based on the distinctions that code catching the exceptions is likely to need, rather than the locations where the exceptions are raised. Aim to answer the question "What went wrong?" programmatically, rather than only stating that "A problem occurred" (see PEP 3151 for an example of this lesson being learned for the builtin exception hierarchy);
    • Not compare boolean values to True or False using == .

      Yes:   if greeting:
      No:    if greeting == True:
      Worse: if greeting is True:
      

Applying that to your code gives the more readable:

class NoBadVersion(Exception):
    pass


def isBadVersion(number):
    """Mocked external API. Obligatory camelCaseName for consistency."""
    return number > 0


def find_bad_version(numbers):
    """Return the index of the first bad version.
    Tries to perform as few external API calls as possible.
    """

    start = 0
    end = len(numbers) - 1

    if isBadVersion(numbers[start]):
        return start

    if not isBadVersion(numbers[end]):
        raise NoBadVersion('all good')

    while start <= end:
        mid = start + (end-start) / 2
        if isBadVersion(numbers[mid]):
            if start == end:
                return end
            end = mid
        else:
            start = mid + 1


if __name__ == "__main__":
    print find_bad_version([0, 0, 0, 1, 1, 1, 1, 1])
    print find_bad_version([0, 0, 0, 0, 0, 0, 0, 1])
\$\endgroup\$
  • 1
    \$\begingroup\$ if for someshit reason number is negative you will return False \$\endgroup\$ – Alex Dec 15 '16 at 13:20
  • 1
    \$\begingroup\$ @Alex You mean, in isBadVersion? Who cares, we are mocking an external API whose details are unknown. I could have changed it to return number != "spam" it wouldn't make any difference. The only thing we need to care about is to keep the tests consistent with this function. \$\endgroup\$ – 409_Conflict Dec 15 '16 at 13:35
  • 1
    \$\begingroup\$ (While I can see where if isBadVersion(numbers[start]) (& end) comes from: what is it good for, does it minimise #calls to isBadVersion()?) \$\endgroup\$ – greybeard Dec 15 '16 at 17:33
  • \$\begingroup\$ Thanks Mathias, do you think if there is a better solution -- for better I mean from algorithm time complexity perspective? Or same time complexity, but less # of calls to isBadVersion? \$\endgroup\$ – Lin Ma Dec 18 '16 at 0:52
  • \$\begingroup\$ @greybeard, good question, I am also think about this when trying to reduce even further # of calls to isBadVersion -- do you have any specific ideas -- showing your idea by code is much clear. \$\endgroup\$ – Lin Ma Dec 18 '16 at 0:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.