
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:
- You know the oldest version is good and the newest is bad.
- Test the version in the middle.
- Good? The first bad one is later. Bad? It's this one or earlier.
- 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):
versionsis 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)returnsTruefor 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_goodonly about log2(n) times.
Write first_bad(versions, is_good):
versionsis 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)returnsTruefor 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_goodonly about log2(n) times.
main.py Python sleeping
Press Run to try your code, then Check to test it.