HackerRank Python: Compress the String!

Compress the String!

In this task, we would like for you to appreciate the usefulness of the groupby() function of itertools . To read more about this function, Check this out .

You are given a string S. Suppose a character ‘’ occurs consecutively X times in the string. Replace these consecutive occurrences of the character ‘c’ with (X,c) in the string.

For a better understanding of the problem, check the explanation.

from itertools import groupby

print(*[(len(list(c)),int(k)) for k, c in groupby(input())])

#input으로 들어온 숫자 예를 들어 1222311을 연속되는 숫자끼리 groupby를 이용하여 묶어줍니다
# 여기서 list(c)를 print 해보면 ['1'],['2','2','2'],['3'],['1','1']가 프린트됩니다
# int(k)는 각 연속된 숫자들을 프린트해줍니다 1,2,3,1
# len(list(c))는 list(c)로 생성된 각 리스트의 길이를 반환합니다. 1,3,1,2
# *는 list comprehension안에서 unpacking을 통해 list가 아닌 tuple을 print해줍니다.