Exercise 2: Three Levels of Nesting, Paint Order Matches Depth Exactly — Possible Solution ==================================================================== THE TEST ------------------------------ inner = block({'background-color': 'green', 'width': '20px', 'height': '20px'}) middle = block({'background-color': 'yellow', 'width': '60px', 'height': '60px'}, children=[inner]) outer = block({'background-color': 'purple'}, children=[middle]) layout_block(outer, root_cb) [cmd.color for cmd in build_display_list(outer)] RESULT ------------------------------ ['purple', 'yellow', 'green'] Outermost (purple) first, middle (yellow) second, innermost (green) last -- matching nesting depth exactly, shallow to deep. WHY THE ORDER GENERALIZES BEYOND TWO LEVELS ------------------------------ build_display_list's own recursive structure is: def build_display_list(layout_box, display_list=None): if display_list is None: display_list = [] paint_background(layout_box, display_list) for child in layout_box.children: build_display_list(child, display_list) return display_list Tracing the call chain for outer -> middle -> inner: 1. build_display_list(outer, []) runs -- paint_background(outer, ...) appends 'purple' FIRST, before the for-loop even starts. 2. The for-loop then calls build_display_list(middle, list_with_purple). THAT call's own paint_background(middle, ...) appends 'yellow' SECOND, again before ITS OWN for-loop starts. 3. middle's for-loop calls build_display_list(inner, list_with_purple_yellow). inner has no children of its own, so its own paint_background call appends 'green' THIRD, and its own (empty) for-loop does nothing further. Because every level appends its OWN background before recursing into its OWN children, and the whole thing is a single shared list passed by reference down through every recursive call, the append order mirrors the call order exactly -- and the call order mirrors tree depth exactly, shallowest first, because each level's own append happens strictly before it ever descends one level deeper. WHY THIS WORKS AS AN ANSWER ------------------------------ This confirms the fix from the chapter's own two-box example isn't a special case that only happens to work for exactly two levels -- the recursive structure itself (append-self-then-recurse) produces correct paint order at ANY depth, by induction: if it's correct for a subtree rooted at any given node (append that node, then each child subtree in turn, each of which is itself correctly ordered by the same reasoning), it's correct for the whole tree. Testing three levels instead of two is what actually exercises this inductive structure, rather than just re-confirming the base case.