Card 06/ 08
Writing the Code Before Asking What the Input Holds
A first draft that starts its maximum at 0 reports a winter week's warmest night as 0 °C, a temperature that never occurred.
Skipping the clarify step lets an assumption into the code that nobody chose. This card shows the most common one, a running maximum that starts at 0, and the two questions that would have caught it. The task is to report the warmest nightly low of a week, given the readings in °C.
A first draft starts the maximum at 0, the habit carried over from counting and summing, and replaces it with any larger reading. On a summer week it works. On a winter week of −3, −1, −4 and −6 no reading beats 0, so the draft reports 0 °C, a temperature that never occurred. An empty week also returns 0, which looks like a real reading. The listing holds the draft and the fix, run on the same week and on an empty one.
def warmest_draft(lows: list[int]) -> int:
warmest = 0
for low in lows:
if low > warmest:
warmest = low
return warmest
def warmest_fixed(lows: list[int]) -> int | None:
if not lows:
return None
warmest = lows[0]
for low in lows[1:]:
if low > warmest:
warmest = low
return warmest
lows = [-3, -1, -4, -6]
print("draft:", warmest_draft(lows))
print("fixed:", warmest_fixed(lows))
print("draft, empty week:", warmest_draft([]))
print("fixed, empty week:", warmest_fixed([]))draft: 0
fixed: -1
draft, empty week: 0
fixed, empty week: NoneTwo questions in step 1 would have caught both faults: "can a reading be negative?" and "can the week be empty?". The fix starts from the first reading, so the answer is always a value that occurred, and it decides that an empty week returns None rather than inventing a temperature. Starting from Java's Integer.MIN_VALUE or TypeScript's -Infinity is the other common repair; it gives the right maximum for any non-empty week, but still returns a made-up value for an empty one, so the empty case needs its own decision whichever start you pick.
The same slip appears wherever a starting value stands in for "nothing yet": a minimum that starts at 0 on positive prices, a best score that starts at 0 when scores can be negative. In each case the hand-worked examples from step 2 only catch it if one of them was chosen at the boundary the clarify step found.
← → move through sections and cards