ProgrammingVery hardGATE CS · Product-company placement
What is printed?
What is printed?
def walk(d, depth=0):
out = []
for k, v in d.items():
out.append(f"{k}{depth}")
if isinstance(v, dict):
out += walk(v, depth + 1)
return out
print(walk({"a": {"b": {}, "c": {"d": 1}}, "e": 2}))- A. ['a0', 'b1', 'c1', 'd2', 'e0']
- B. ['a0', 'e0', 'b1', 'c1', 'd2']
- C. ['a0', 'b1', 'c1', 'e0']
- D. ['a0', 'b1', 'c1', 'd2', 'e1']
Correct answer: A. ['a0', 'b1', 'c1', 'd2', 'e0']
The recursion is depth-first and preserves dict insertion order. 'b' maps to an empty dict, which is still a dict, so recursion happens but adds nothing; 'd' maps to 1, so it is listed but not recursed.
More Python Programming questions
- What is printed? python def hanoi(n): return 0 if n == 0 else 2 hanoi(n - 1) + 1 def calls(n): return 1 if n == 0 else 1 + 2 calls(n - 1)…
- What is printed? python import sys def depth(n): try: return depth(n + 1) except RecursionError: return n d = depth(0) print(d > 500, d <…
- What is printed? python x = 0 def a(): global x x = 1 def b(): global x x += 10 b() return x print(a(), x)
- What is printed? python class A: n = [] m = 0 a, b = A(), A() a.n.append(1) a.m += 1 b.n = [2] print(A.n, A.m, a.n, b.n, a.m, b.m)
- What is printed? python x = [0, 1, 2, 3, 4, 5] print(x[1::2], x[-1::-2], x[::-1][::2] == x[::-2])
- What is printed? python m = [[1, 2, 3], [4, 5, 6]] t = list(zip(m)) print(t, [list(r) for r in zip(t)] == m, [x for row in m for x in…