ProgrammingVery hardProduct company OA
What is printed?
What is printed?
from itertools import groupby
s = "aabbbaac"
g1 = [(k, len(list(v))) for k, v in groupby(s)]
g2 = {k: len(list(v)) for k, v in groupby(s)}
print(len(g1), g2, [k for k, v in groupby(sorted(s))], max(g1, key=lambda p: p[1]))- A. 3 {'a': 4, 'b': 3, 'c': 1} ['a', 'b', 'c'] ('a', 4)
- B. 4 {'a': 4, 'b': 3, 'c': 1} ['a', 'b', 'c'] ('b', 3)
- C. 4 {'a': 2, 'b': 3, 'c': 1} ['a', 'b', 'c'] ('b', 3)
- D. 4 {'a': 2, 'b': 3, 'c': 1} ['a', 'b', 'a', 'c'] ('b', 3)
Correct answer: C. 4 {'a': 2, 'b': 3, 'c': 1} ['a', 'b', 'c'] ('b', 3)
groupby only merges CONSECUTIVE equal items (it is a run-length grouper, not SQL GROUP BY). The runs are aa, bbb, aa, c → 4 groups. In the dict comprehension the second run of 'a' overwrites the first, so 'a' maps to 2, not 4. Sorting first makes equal letters adjacent → keys a, b, c. The longest run is ('b', 3). The option with 3 groups and 'a': 4 is what you get only after sorting the input.
More Python Programming questions
- What is printed? python print("abc" 2 + "d", len("abc" 0))
- What is printed? python x = [10, 20, 30, 40, 50] print(x[-1], x[len(x) // 2], x[-2:])
- What is printed? python s = "Python" print(s.find("th"), s.find("z"), s.upper()[1:3])
- What is printed? python s = "a-b-c-d" print(s.split("-", 2), s.rsplit("-", 1))
- What is printed? python print("hello world".title(), "ab".center(6, ""), "42".zfill(5), "-7".zfill(4))
- What is printed? python d = dict(zip("abc", range(3))) d.update({"b": 9, "d": 1}) print(list(d.items())[1], sum(d.values()), len(d))