ProgrammingVery hardGATE CS · Product-company placement
What is printed? (Output lines are shown separated by " / ".)
What is printed? (Output lines are shown separated by " / ".)
from itertools import groupby data = [1, 1, 2, 1, 3, 3] print([(k, len(list(g))) for k, g in groupby(data)]) groups = groupby(data) saved = [g for k, g in groups] print(len(saved), [list(g) for g in saved][0])
- A. [(1, 3), (2, 1), (3, 2)] / 3 [1, 1, 1]
- B. [(1, 2), (2, 1), (1, 1), (3, 2)] / 4 []
- C. [(1, 2), (2, 1), (1, 1), (3, 2)] / 4 [1, 1]
- D. [(1, 3), (2, 1), (3, 2)] / 3 []
Correct answer: B. [(1, 2), (2, 1), (1, 1), (3, 2)] / 4 []
groupby groups only consecutive equal items, so 1 appears as two separate groups. All groups share one underlying iterator: advancing groupby to the next key exhausts the previous group, so groups saved for later come out empty.
More Python Programming questions
- What is printed? python from functools import reduce print(reduce(lambda a, b: a 10 + b, [1, 2, 3]), reduce(lambda a, b: a + b, [], 7)…
- What is printed? python from functools import lrucache calls = 0 @lrucache(maxsize=2) def f(x): global calls calls += 1 return x for v in…
- What is printed? (Output lines are shown separated by " / ".) python from functools import partial def power(base, exp): return base exp…
- What is printed? python x = [3, 1, 2] y = sorted(x) z = reversed(x) x.append(0) print(y, list(z))
- What is printed? python m = map(lambda v: v 2, [1, 2, 3]) f = filter(None, [0, 1, 2]) print(list(m), list(m), next(f), list(zip(f, "xyz")))
- What is printed? python a = [1, 2, 3] for i, v in enumerate(a): a[i] = v 2 if i == 0: a.append(9) if len(a) > 4: break print(a)