Compress the String!

  • + 1 comment

    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

      Wow. Incredibly long and complex. I wrote a solution without groupby(), too, but it was simple. Maybe the "sliding window" technique is not suited to this problem.