ProgrammingVery hardProduct company OA
What is printed?
What is printed?
it = iter(range(10)) a = list(zip(it, "ab")) b = next(it) c = [x for x in it if next(it, 0) % 3] print(a, b, c)
- A. [(0, 'a'), (1, 'b')] 2 [3, 5, 7]
- B. [(0, 'a'), (1, 'b')] 3 [4, 6, 8]
- C. [(0, 'a'), (1, 'b')] 3 [4, 6]
- D. [(0, 'a'), (1, 'b')] 2 [4, 7]
Correct answer: C. [(0, 'a'), (1, 'b')] 3 [4, 6]
zip pulls from its arguments left to right. For the third tuple it first takes 2 from it, then finds the string exhausted and stops – the 2 is already consumed and lost. So next(it) is 3. In the comprehension each kept x is followed by a second next() inside the condition: x = 4 (peeks 5, 5 % 3 = 2, keep), x = 6 (peeks 7, keep), x = 8 (peeks 9, 9 % 3 = 0, drop). Output: [(0, 'a'), (1, 'b')] 3 [4, 6]. Putting the shorter iterable first, zip('ab', it), would not have lost an element.
More Python Programming questions
- What is printed? python def tag(t): print("make", t, end=" ") def deco(fn): print("wrap", t, end=" ") def inner(a): return f"<{t}>" +…
- What is printed? python x = 1 class K: x = 2 a = [x for in range(2)] b = [x i for i in range(x + 1)] def m(self): return x print(K.a, K.b…
- What is printed? python data = [5, 3, 8, 1] out = [] while (n := len(data)) > 1: first, data = data data[-1] += first out.append((n…
- What is printed? python from functools import lrucache @lrucache(maxsize=None) def path(n): return [0] if n == 0 else path(n - 1) + [n] p…
- What is printed? python class Seq: def init(self, n): self.n = n; self.calls = 0 def getitem(self, i): self.calls += 1 if i >= self.n…
- What is printed? python import heapq tasks = [(2, "write"), (1, "test"), (2, "ship"), (1, "plan")] h = [] for i, (p, name) in…