Code

Bisect the Changes

"It worked last month!" Since then, the bonus function was changed 12 times, and somewhere along the way it broke. Which change did it?

Checking every version one by one is slow. Instead, bisect:

  1. You know the oldest version is good and the newest is bad.
  2. Test the version in the middle.
  3. Good? The first bad one is later. Bad? It's this one or earlier.
  4. Repeat on the half that's left.

Each check cuts the suspects in half. 1,000 versions need only about 10 checks! It's binary search, used on history. Real teams do this with git bisect, which checks out each middle version for you.

Keep two markers: low (a version known to be good) and high (a version known to be bad). When they're next to each other, high is the first bad version.

Assignment

Write first_bad(versions, is_good):

  • versions is a list, oldest first. versions[0] is good and the last one is bad. Once a version is bad, every later one is bad too.
  • is_good(version) returns True for a good version. Pass it the version itself (versions[mid]), not the index.
  • Return the index of the first bad version.
  • Bisect! Pip checks that you call is_good only about log2(n) times.