Skip to content
ExamSpine

Trace it

Trace: p2 b134 stack trace

Python code10 rows to fill4 marks

Complete the trace table for this Python code. A school code editor checks brackets using stack as a stack: append pushes onto the top (the right-hand end) and pop() removes the top item and gives it back. The stack column holds the whole stack in square brackets, like ["("], after each change. Then answer the question below the table. [4]

Line 1: text = "[(a)]"
Line 2: stack = []
Line 3: for ch in text:
Line 4, indented 1 level: if ch == "(" or ch == "[":
Line 5, indented 2 levels: stack.append(ch)
Line 6, indented 1 level: elif ch == ")" or ch == "]":
Line 7, indented 2 levels: top = stack.pop()

Fill in one row each time a line changes ch, stack or top. The table already has the right number of rows. In each row, write only what that line changes; you can leave the other cells empty or copy their values down. Write values the way Python shows them: 3 and 3.0 are different, and text goes in quotes.

Rowchstacktop
1
2
3
4
5
6
7
8
9
10