ProgrammingHardTCS CodeVita · Infosys HackWithInfy
What is printed?
What is printed?
from itertools import groupby
rows = [('b', 2), ('a', 1), ('b', 5), ('a', 3)]
ok = {k: sum(v for _, v in g) for k, g in groupby(sorted(rows), key=lambda r: r[0])}
bad = {k: sum(v for _, v in g) for k, g in groupby(rows, key=lambda r: r[0])}
print(ok, bad)- A. {'a': 4, 'b': 7} {'a': 4, 'b': 7}
- B. {'b': 7, 'a': 4} {'b': 5, 'a': 3}
- C. {'a': 4, 'b': 7} {'b': 5, 'a': 3}
- D. {'a': 4, 'b': 7} {'a': 3, 'b': 5}
Correct answer: C. {'a': 4, 'b': 7} {'b': 5, 'a': 3}
groupby merges only consecutive equal keys, so on the unsorted rows the later groups overwrite earlier dict entries. Sorting first gives the true totals.
More Python Programming questions
- What is printed? python def lru(cap, ops): d = {} out = [] for op, k in ops: if op == 'get': if k in d: v = d.pop(k) d[k] = v…
- What is printed? python from itertools import combinations a = [1, 2, 3, 4] cnt = 0 for r in range(1, len(a) + 1): for c in…
- What is printed? python from collections import Counter def pairseq(a, t): c = Counter(a) total = 0 for x in c: y = t - x if x < y: total…
- What is printed? python import bisect def minlen(a, s): pre = [0] for x in a: pre.append(pre[-1] + x) best = float('inf') for i in…
- What is printed? python people = [('Ann', 30), ('Bob', 25), ('Cid', 30), ('Dan', 25)] s1 = sorted(people, key=lambda p: p[0]) s2 =…
- What is printed? python from itertools import accumulate h = [3, 1, 4, 1, 5, 9, 2, 6] vis = [x for x, m in zip(h, [0] + list(accumulate(h…