Exercise 2: A Fully Off-Canvas Rect Requires No Special Case — Possible Solution ==================================================================== THE TEST ------------------------------ canvas = Canvas(10, 10, background=(255, 255, 255)) fill_rect(canvas, Rect(20, 20, 5, 5), (0, 255, 0)) all(px == (255, 255, 255) for row in canvas.pixels for px in row) RESULT ------------------------------ True -- every pixel on the canvas is still the original white background. Not one pixel was touched. WHY THE CLIPPING FORMULA HANDLES THIS WITHOUT A SEPARATE CHECK ------------------------------ fill_rect computes: x0 = max(0, int(rect.x)) = max(0, 20) = 20 y0 = max(0, int(rect.y)) = max(0, 20) = 20 x1 = min(canvas.width, int(rect.x + rect.width)) = min(10, 25) = 10 y1 = min(canvas.height, int(rect.y + rect.height)) = min(10, 25) = 10 x0 (20) ends up GREATER than x1 (10), and likewise y0 (20) is greater than y1 (10). The fill loop is: for y in range(y0, y1): # range(20, 10) for x in range(x0, x1): # range(20, 10) canvas.pixels[y][x] = color range(20, 10) -- a start value larger than the stop value, with the default step of +1 -- produces an EMPTY sequence in Python. This is completely standard, well-defined Python behavior (range() never raises an error for a "backwards" range; it just yields nothing), not a special case fill_rect has to detect and branch around. The outer for-loop body simply never executes, so canvas.pixels is never touched at all. WHY THIS WORKS AS AN ANSWER ------------------------------ This is the real payoff of using max()/min() clamping rather than an explicit "does this rect overlap the canvas at all?" boolean check followed by a separate branch: the SAME two lines of clamping code correctly handle every case -- a rect fully on-canvas, a rect partially overlapping an edge (Chapter 8's own main example), and a rect fully off-canvas -- without the function needing to know or care which situation it's actually in. The "fully off-canvas" case isn't handled by special logic; it emerges automatically as the specific combination of clamped values where the resulting range happens to be empty. This is a common, elegant pattern in real graphics code: express bounds-checking as a data transformation (clamp the coordinates) rather than as a control-flow decision (branch on whether they're valid), and edge cases like "no overlap at all" resolve themselves for free.