Question 20
What is the output of the following code? [3 marks]
Solution
Initialize inbox to be a list with integers 9, 2, 5, 0, 0, 4, 3, 3, 0, 1, 8, 7, 0.
Variables outbox and temp are an empty tuple and list respectively.
Trace the program flow by iterating through each element in inbox.
item |
item != 0? |
New temp |
len(temp) != 0? |
smallest |
comp |
New smallest: min(smallest, comp) |
New outbox |
|---|---|---|---|---|---|---|---|
9 |
True |
[9] |
|||||
2 |
True |
[9, 2] |
|||||
5 |
True |
[9, 2, 5] |
|||||
0 |
False |
[9, 2, 5] |
True |
9 |
2 |
min(9, 2) = 2 |
|
2 |
5 |
min(2, 5) = 2 |
() + (2,) = (2,) |
||||
0 |
False |
[] |
False |
||||
4 |
True |
[4] |
|||||
3 |
True |
[4, 3] |
|||||
3 |
True |
[4, 3, 3] |
|||||
0 |
False |
[4, 3, 3] |
True |
4 |
3 |
min(4, 3) = 3 |
|
3 |
3 |
min(3, 3) = 3 |
(2,) + (3,) = (2, 3) |
||||
1 |
True |
[1] |
|||||
8 |
True |
[1, 8] |
|||||
7 |
True |
[1, 8, 7] |
|||||
0 |
False |
[1, 8, 7] |
True |
1 |
8 |
min(1, 8) = 1 |
|
1 |
7 |
min(1, 7) = 1 |
(2, 3) + (1,) = (2, 3, 1) |