ProgrammingModerateGATE CS · Product-company placement
What is printed?
What is printed?
d = {"x": [1, 2], "y": [3]}
flat = [v for vs in d.values() for v in vs]
lengths = {k: len(v) for k, v in d.items()}
print(flat, lengths, max(lengths, key=lengths.get))- A. [1, 2, 3] {'x': 2, 'y': 1} [1, 2]
- B. [1, 2, 3] {'x': 2, 'y': 1} 2
- C. [1, 2, 3] {'x': 2, 'y': 1} y
- D. [1, 2, 3] {'x': 2, 'y': 1} x
Correct answer: D. [1, 2, 3] {'x': 2, 'y': 1} x
In a nested comprehension the for clauses read left to right as nested loops, flattening the lists. max over a dict iterates keys and, with key=lengths.get, picks the key with the largest value.
More Python Programming questions
- What is printed? python def f(n): out = [] while n: n, r = divmod(n, -2) if r < 0: n, r = n + 1, r + 2 out.append(str(r)) return…
- What is printed? python def gen(n): if n == 0: yield "" return for s in gen(n - 1): yield s + "0" if not s.endswith("1"): yield s + "1"…
- What is printed? python cache = {} def ways(n): if n < 0: return 0 if n == 0: return 1 if n not in cache: cache[n] = ways(n - 1) + ways(n…
- What is printed? python def perms(s): if len(s) <= 1: return [s] out = [] for i, c in enumerate(s): for p in perms(s[:i] + s[i + 1:])…
- What is printed? python def makeops(): ops = {} for name, sym in [("add", "+"), ("mul", "")]: ops[name] = eval(f"lambda a, b: a {sym} b")…
- What is printed? python x = 1 def f(): return x def g(): x = 2 return f() def h(): global x x = 3 return f() print(g(), h(), f())