How does halving the search space with one well-placed print statement turn a mysterious palindrome bug into a few quick experiments?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
You are given the buggy is_pal from the video and five test cases in cases, each a (input, expected) pair. Run every input through the function, keep the inputs whose answer disagrees with the expected answer, and assign the shortest of those to simplest_failing.
(Hint: len() measures a list, and min() takes an optional key= argument.)
# The buggy is_pal from the video, plus five (input, expected) pairs.
def is_pal(x):
temp = x
temp.reverse
if temp == x:
return True
else:
return False
cases = [
(list('abcba'), True),
(list('ab'), False),
(list('aa'), True),
(list('xyzzy'), False),
(list('abcdefghijklm'), False),
]Debugging as hypothesis testing
Record the habit of comparing the failing test cases for something in common, forming a hypothesis about the one piece of code at fault, and checking it against another failing case.
Halving the search space each time
Write the procedure: print halfway through the code, decide from the printed values whether the bug sits before or after that point, then print at the quarter mark and repeat.
Worked session on the broken is_pal
Trace the session: pick ab as the simplest failing input, read the printed ['a', 'b'] ['a', 'b'], apply the fixes temp.reverse() and a copy of x, then re-run abcba.