easy +8 pts

Groupby Consecutive

Implement a generator that groups consecutive identical elements from an iterable.

Write a generator function `groupby_consecutive(iterable)` that takes any iterable (e.g., list, string, tuple) and yields pairs `[value, list_of_occurrences]` for each maximal run of consecutive equal elements in the order they appear. - The input may contain any hashable elements (numbers, strings, etc.). - Each yielded pair must be a list of two items: the first item is the value of the run, the second item is a list of all occurrences in that run. - The function must be a generator: it should yield results lazily and not build the full output list upfront. - Do not use `itertools.groupby`. **Signature:** ```python def groupby_consecutive(iterable): ... ``` **Returns:** A generator that yields `[value, occurrences_list]` pairs.

Constraints

The input iterable has at most 10^6 elements. The elements are hashable. The function should use O(k) memory for the largest run when yielding, not O(n) for all elements.

Example

>>> list(groupby_consecutive([1, 1, 2, 3, 3, 3]))
[[1, [1, 1]], [2, [2]], [3, [3, 3, 3]]]
>>> list(groupby_consecutive("aabbbaa"))
[['a', ['a', 'a']], ['b', ['b', 'b', 'b']], ['a', ['a', 'a']]]
>>> list(groupby_consecutive([]))
[]
8 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Iterate over the iterable while maintaining a current value and a list of its occurrences.
When you see a new value that differs from the current, yield the previous group as a list [value, [occurrences]] and start a new one.
Don't forget to yield the last group after the loop ends.
Using a generator function means you need the `yield` keyword, not `return`.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.