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.
- Prepare
- Python
- Itertools
- Compress the String!
- Discussions
Compress the String!
Compress the String!
Sort by
recency
|
868 Discussions
|
Please Login in order to post a comment
from itertools import groupby s1=(input()) list1=[] for k, g in groupby(s1):
list1.append((len(tuple(g)),int(k))) print(*list1)
s = input()
compressed = [] count = 1
for i in range(1, len(s)): if s[i] == s[i - 1]: count += 1 else: compressed.append((count, int(s[i - 1]))) count = 1
compressed.append((count, int(s[-1])))
print(' '.join(str(tup) for tup in compressed))
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. """
from itertools import groupby
if name == 'main': S = str(input()) results = [(len(list(g)),int(k)) for k,g in groupby(S)] result_as_str = list(map(lambda result: str(result), results)) print(' '.join(result_as_str))