Exercise 2: Chained Implied Closes — Possible Solution ==================================================================== THE TEST ------------------------------ parse_html("

A

B

C

") RESULT ------------------------------ <#document>

'A'

'B'

'C' Exactly THREE top-level

elements: "A", "B", and "C" -- each one its own separate sibling, none nested inside another. STACK TRACE AT EACH opentag EVENT ------------------------------ Start: stack = [root] 1st

(opens): tok.name='p' in P_CLOSING_TAGS, but stack[-1] is root, not a p -> no pop. Push p1. stack = [root, p1] 'A' appended to p1. p1.children = ['A'] 2nd

(opens): tok.name='p' in P_CLOSING_TAGS, stack[-1]=p1, top_tag='p' -> MATCH -> pop p1. stack = [root] Push p2. stack = [root, p2] 'B' appended to p2. p2.children = ['B'] 3rd

(opens): tok.name='p' in P_CLOSING_TAGS, stack[-1]=p2, top_tag='p' -> MATCH -> pop p2. stack = [root] Push p3. stack = [root, p3] 'C' appended to p3. p3.children = ['C']

(closes): search stack for a 'p' -> stack[-1]=p3 matches -> pop. stack = [root] Final: root.children = [p1, p2, p3] WHY THIS CHAINS CORRECTLY WITH NO EXTRA CODE ------------------------------ The check `stack[-1]` (top_tag == 'p') is re-evaluated fresh, from scratch, every single time a new opentag token arrives -- it isn't a one-shot check that only fires once per document. Because popping p1 and immediately pushing p2 leaves p2 sitting at the exact same "top of stack" position p1 occupied a moment earlier, the THIRD

's own check finds p2 there and pops it using the identical logic, with no memory of how many times this has already happened. The rule is purely local -- "is the thing currently on top of the stack a p" -- which is exactly what makes it correctly self-chain across any number of consecutive

tags without needing a counter, a loop, or any special-casing for "this is the second time" versus "this is the first time."