Compress the String!

Sort by

recency

|

868 Discussions

|

  • + 0 comments

    from itertools import groupby s1=(input()) list1=[] for k, g in groupby(s1):
    list1.append((len(tuple(g)),int(k))) print(*list1)

  • + 0 comments

    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))

  • + 0 comments

    Notes

    itertools.groupby(iterable)

    • 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. """

  • + 0 comments

    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))

  • + 0 comments
    from itertools import groupby
    s=input()
    for k,g in groupby(s):
        print(tuple([len(list(g)),int(k)]),end=' ')