ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
import heapq
g = {'A': [('B', 1), ('C', 4)], 'B': [('C', 2), ('D', 5)], 'C': [('D', 1)], 'D': []}
dist = {k: float('inf') for k in g}
dist['A'] = 0
pq = [(0, 'A')]
while pq:
    d, u = heapq.heappop(pq)
    if d > dist[u]:
        continue
    for v, w in g[u]:
        if d + w < dist[v]:
            dist[v] = d + w
            heapq.heappush(pq, (dist[v], v))
print(dist['D'], dist)
  1. A. 4 {'A': 0, 'B': 1, 'C': 4, 'D': 4}
  2. B. 5 {'A': 0, 'B': 1, 'C': 3, 'D': 5}
  3. C. 4 {'A': 0, 'B': 1, 'C': 3, 'D': 4}
  4. D. 6 {'A': 0, 'B': 1, 'C': 3, 'D': 6}

Correct answer: C. 4 {'A': 0, 'B': 1, 'C': 3, 'D': 4}

The shortest path A to D goes A to B to C to D with cost 1 + 2 + 1 = 4, which beats A to B to D with cost 6. The stale-entry check skips heap entries whose distance is out of date.

More Python Programming questions

Exams that ask this topic