Compress the String!

Sort by

recency

|

848 Discussions

|

  • + 0 comments

    # Enter your code here. Read input from STDIN. Print output to STDOUT from itertools import groupby

    s= input().strip()

    for key , group in groupby(s): print(f"({len(list(group))}, {key})",end=' ')

  • + 0 comments
    from itertools import groupby
    
    my_string = input()
    
    for my_iterable , my_key in groupby(my_string):
        print(f"({len(list(my_key))}, {my_iterable})", end =" ") 
    
  • + 0 comments
    from itertools import groupby
    S = input()
    ll = [(len(list(g)), int(k))  for k, g in groupby(S)]
    for x in ll:
        print(x, end=" ")
    
  • + 0 comments

    Without itertools using sliding window concept.

    from collections import defaultdict
    strings = str(input())
    
    dicts = defaultdict()
    answers = []
    left = 0
    right = 1
    
    if len(strings) == 1:
        print(f'({1}, {int(strings)})')
    
    while(right < len(strings)):
        if strings[left] == strings[right]:
            if strings[left] not in dicts.keys():
                dicts[strings[left]] = 2
            else:
                dicts[strings[left]] += 1
            if right == len(strings) - 1:
                tuples = tuple([dicts[strings[left]],int(strings[left])])
                answers.append(tuples)
                dicts = defaultdict()
                    
        else:
            if strings[left] not in dicts.keys():
                dicts[strings[left]] = 1
            tuples = tuple([dicts[strings[left]],int(strings[left])])
            answers.append(tuples)
            dicts = defaultdict()
            dicts[strings[right]] = 1
            left = right
            if right == len(strings) - 1:
                dicts[strings[left]] = 1
                tuples = tuple([dicts[strings[left]],int(strings[left])])
                answers.append(tuples)
                
        right += 1
        
    		
    
        
    print(' '.join(f'({x}, {y})' for x,y in answers))
    
  • + 0 comments
    from itertools import groupby
    
    S = input()
    result = []
    
    for num, group in groupby(S):
        length = len(list(group))
        result.append((length, int(num)))
    
    print(" ".join(str(x) for x in result))