ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy
What is printed?
What is printed?
from collections import deque
n = 4
edges = [(0, 2), (1, 2), (2, 3), (0, 3)]
indeg = [0] * n
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
q = deque(i for i in range(n) 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. [1, 0, 2, 3]
- C. [0, 2, 1, 3]
- D. [0, 1, 2, 3]
Correct answer: D. [0, 1, 2, 3]
Kahn's algorithm starts with the in-degree-zero nodes 0 and 1 in index order. Popping 0 lowers the in-degree of 2 and 3, but 2 still waits for node 1. Popping 1 then releases 2, and then 3.
More Python Programming questions
- What is printed? python def cnt(xs, T): xs = sorted(xs) lo, hi, total = 0, len(xs) - 1, 0 while lo < hi: if xs[lo] + xs[hi] <= T: total +=…
- What is printed? python def knap(items, cap): dp = [0] (cap + 1) for w, v in items: for c in range(cap, w - 1, -1): dp[c] = max(dp[c]…
- What is printed? python import heapq h = [] for x in [4, 9, 1, 7]: heapq.heappush(h, -x) print(-heapq.heappop(h), -h[0])
- What is printed? python from functools import partial def power(base, exp): return base exp sq = partial(power, exp=2) cubeofthree =…
- What is printed? python import itertools it = itertools.count(10, 5) print(list(itertools.islice(it, 3)), next(it))
- What is printed? python words = ['b', 'a', 'c'] pairs = list(zip(sorted(words), range(10, 13))) print(pairs, dict(pairs)['c']…