ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy
What is printed?
What is printed?
parent = list(range(5))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a, b):
parent[find(a)] = find(b)
union(0, 1)
union(2, 3)
union(1, 3)
print(find(0), parent)- A. 3 [0, 1, 2, 3, 4]
- B. 3 [3, 3, 3, 3, 4]
- C. 3 [1, 3, 3, 3, 4]
- D. 1 [1, 3, 3, 3, 4]
Correct answer: B. 3 [3, 3, 3, 3, 4]
After the three unions parent is [1, 3, 3, 3, 4]. find(0) uses path halving: parent[0] becomes parent[1], which is 3, and then the walk reaches the root 3. The array is left as [3, 3, 3, 3, 4].
More Python Programming questions
- What is printed? python trie = {} for w in ['car', 'cat', 'dog']: node = trie for ch in w: node = node.setdefault(ch, {}) node['#'] = True…
- What is printed? python h = 0 for ch in 'abc': h = (h 31 + ord(ch)) % 1000 print(h)
- What is printed? python grid = ['a..', '.a.', '...'] cnt = sum(row.count('.') for row in grid) diag = ''.join(grid[i][i] for i in…
- What is printed? python from collections import Counter c = Counter('abracadabra') print(sum(v for v in c.values() if v % 2), len(c)…
- What is printed? python x = 0b1010 y = 0o17 z = 0xFF print(x ^ y, x | z, z >> 4, y & ~x)
- What is printed? python a = 'Python' print(a[::-1][1:4], a[-2:] + a[:2], a.upper()[::2])