← Quiz: Topological Sort: all 15 questions
Quiz: Topological Sort · Question 13 of 15
What does this print? (code)
What does this print?
from collections import deque
nodes = [1, 2, 3, 4]
adj = {1: [2, 3], 2: [4], 3: [4], 4: []}
indeg = {1: 0, 2: 1, 3: 1, 4: 2}
q = deque(n for n in nodes if indeg[n] == 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.[1, 2, 4, 3]
- B.[4, 3, 2, 1]
- C.[1, 3, 2, 4]
- D.[1, 2, 3, 4]
Answer & explanation
Correct answer: [1, 2, 3, 4]
1 frees 2 and 3. Node 4 waits until both 2 and 3 are done, so it comes last.
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 →