← Quiz: Topological Sort: all 15 questions
Quiz: Topological Sort · Question 3 of 15
What does this print? (code)
What does this print?
from collections import deque
edges = [(0, 1), (0, 2), (1, 3), (2, 3)]
indeg = [0] * 4
adj = [[] for _ in range(4)]
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
q = deque(i for i in range(4) if indeg[i] == 0)
order = []
while q:
u = q.popleft()
order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
print(order)
- A.[0, 1, 3, 2]
- B.[3, 1, 2, 0]
- C.[0, 1, 2, 3]
- D.[0, 2, 1, 3]
Answer & explanation
Correct answer: [0, 1, 2, 3]
0 frees 1 and 2 (in that order); 3 waits until both 1 and 2 are taken.
Can you get the rest right without peeking?
Take the timed Quiz: Topological Sort quiz free. Pass it to earn XP and count towards your certificate.
Start the quiz →