We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Groups consecutive same elements together
Example: "1222311"
Groups = ['1'], ['2','2','2'], ['3'], ['1','1']
For each group:
key → the element value (like '1', '2', '3')
group → an iterator containing the consecutive elements
Important about group:
1) group is an iterator, not a list.
2) Printing group directly shows only an object address.
3) Use list(group) or loop to actually see the values.
4) group (iterator) can be used only once. After consuming, it becomes empty.
Common use cases:
- len(list(group)) → gives count of elements in that group.
- (key, list(group)) → shows the group values with their key.
"""
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Compress the String!
You are viewing a single comment's thread. Return to all comments →
Notes
itertools.groupby(iterable)
For each group: key → the element value (like '1', '2', '3') group → an iterator containing the consecutive elements
Important about group: 1) group is an iterator, not a list. 2) Printing group directly shows only an object address. 3) Use list(group) or loop to actually see the values. 4) group (iterator) can be used only once. After consuming, it becomes empty.
Common use cases: - len(list(group)) → gives count of elements in that group. - (key, list(group)) → shows the group values with their key. """