ProgrammingVery hardInfosys HackWithInfy · TCS CodeVita
What is printed?
What is printed?
from collections import deque
def zero_one(n, edges, src):
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
adj[v].append((u, w))
INF = float('inf')
d = [INF] * n
d[src] = 0
dq = deque([src])
while dq:
u = dq.popleft()
for v, w in adj[u]:
if d[u] + w < d[v]:
d[v] = d[u] + w
if w == 0:
dq.appendleft(v)
else:
dq.append(v)
return d
print(zero_one(4, [(0, 1, 0), (1, 2, 1), (0, 2, 1), (2, 3, 0)], 0))- A. [0, 1, 1, 1]
- B. [0, 0, 1, 2]
- C. [0, 0, 0, 1]
- D. [0, 0, 1, 1]
Correct answer: D. [0, 0, 1, 1]
Weight-0 edges push to the front of the deque and weight-1 edges to the back, so the deque stays ordered by distance. Vertices 1 and 3 are reached through weight-0 edges, while vertex 2 costs 1.
More Python Programming questions
- What is printed? python from collections import deque def ladder(begin, end, words): S = set(words) q = deque([(begin, 1)]) seen = {begin}…
- What is printed? python def can(a): s = sum(a) if s % 2: return False t = s // 2 dp = [False] (t + 1) dp[0] = True for x in a: for v in…
- What is printed? python def paths(g): R, C = len(g), len(g[0]) dp = [[0] C for in range(R)] dp[0][0] = 0 if g[0][0] else 1 for r in…
- What is printed? python def cool(p): hold, sold, rest = float('-inf'), 0, 0 for x in p: hold, sold, rest = max(hold, rest - x), hold + x…
- What is printed? python import bisect def inv(a): s, c = [], 0 for x in a: c += len(s) - bisect.bisectright(s, x) bisect.insort(s, x)…
- What is printed? python import bisect a = [10, 20, 20, 30] print([bisect.bisectleft(a, x) for x in (20, 25, 5, 40)])