ProgrammingVery hardCodeforces-style · placement coding round
What is printed?
What is printed?
import heapq
def topo(n, edges):
indeg = [0] * n
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
h = [i for i in range(n) if indeg[i] == 0]
heapq.heapify(h)
out = []
while h:
u = heapq.heappop(h)
out.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
heapq.heappush(h, v)
return out
print(topo(4, [(3, 0), (1, 0), (2, 0)]), topo(3, [(2, 0), (2, 1)]))- A. [1, 2, 3, 0] [2, 0, 1]
- B. [3, 1, 2, 0] [2, 0, 1]
- C. [1, 2, 3, 0] [0, 1, 2]
- D. [1, 2, 0, 3] [2, 1, 0]
Correct answer: A. [1, 2, 3, 0] [2, 0, 1]
A min-heap of zero in-degree nodes gives the lexicographically smallest order. In the first graph 1, 2 and 3 come before 0, which becomes free only after all three edges are removed.
More Python Programming questions
- Which operation is O(1) amortised in CPython and removes the first item, while list.pop(0) is O(n)?
- What is printed? python print(sorted('bca', reverse=True)[0], 'bca'.index('c'))
- What is printed? python from collections import defaultdict d = defaultdict(int) d['x'] += 2 d['y'] print(dict(d))
- What is printed? python print(list(map(pow, [2, 3], [3, 2])))
- What is printed? python print(min(['10', '9', '2']), min([10, 9, 2]))
- What is printed? python s = {1, 2} t = s t |= {3} print(s, s is t)