Question 15
Back to Exercise
What is the output of the following Python program?
from itertools import takewhile, groupby
print(list(takewhile(lambda n: n < 5, [1, 3, 6, 2, 4])))
print([(k, len(list(g))) for k, g in groupby("aaabccaa")])
- A [1, 3, 2, 4] [('a', 5), ('b', 1), ('c', 2)]
- B [1, 3] [('a', 5), ('b', 1), ('c', 2)]
- C [1, 3, 2, 4] [('a', 3), ('b', 1), ('c', 2), ('a', 2)]
- D [1, 3] [('a', 3), ('b', 1), ('c', 2), ('a', 2)] Correct
Correct Answer: Option D
takewhile stops at the first failing item (6) and never looks further. groupby groups only neighbouring equal items, so the two runs of "a" are separate groups.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!