Skip to content
ExamSpine

Trace it

Trace: p2 b2 library trace

Python code9 rows to fill4 marks

Complete the trace table for this Python code. A school library keeps its book IDs in ids, sorted from smallest to largest. This code is a binary search for the book with ID 150. // divides and keeps only the whole number part, and found stays -1 until the book is found. Then answer the question below the table. [4]

Line 1: ids = [104, 117, 123, 138, 150, 162, 171]
Line 2: target = 150
Line 3: low = 0
Line 4: high = len(ids) - 1
Line 5: found = -1
Line 6: while low <= high and found == -1:
Line 7, indented 1 level: mid = (low + high) // 2
Line 8, indented 1 level: if ids[mid] == target:
Line 9, indented 2 levels: found = mid
Line 10, indented 1 level: elif ids[mid] < target:
Line 11, indented 2 levels: low = mid + 1
Line 12, indented 1 level: else:
Line 13, indented 2 levels: high = mid - 1

Fill in one row each time a line changes low, high, mid or found. 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.

Rowlowhighmidfound
1
2
3
4
5
6
7
8
9