Prepare > Python > Itertools > Compress the String!

2023. 9. 20. 22:14HackerRank-Python

 

Compress the String! | HackerRank

groupby()

www.hackerrank.com

 

문제


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

 

Input Format

A single line of input consisting of the string S.

Output Format

A single line of output consisting of the modified string.

Constraints

All the characters of  denote integers between  and .

 

=> 숫자로 이뤄진 문자열 S를 줄건데, 그 안에 'c'가 X번 반복되면, (X, c)형태로 바꾸어 출력해라

 

 

 

 

코드


from itertools import groupby

for key, group in groupby(input()):
   print('({}, {})'.format(len(list(group)), key), end=" ")

 

 

 

 

노트


from itertools import groupby

for key, group in groupby(input()):
    print(key)
    print(group)
    

"""
1
<itertools._grouper object at 0x7f9d1b6258d0>
2
<itertools._grouper object at 0x7f9d1b625c90>
3
<itertools._grouper object at 0x7f9d1b6258d0>
1
<itertools._grouper object at 0x7f9d1b625c90>
"""

 

from itertools import groupby

for key, group in groupby(input()):
    print(key)
    print(list(group))

"""
1
['1']
2
['2', '2', '2']
3
['3']
1
['1', '1']
"""

 

  • groupby에 대한 공부가 필요할 듯 하다

 

 

 

두 번째 시도

S = input() + '@'


counter=1

for i in range(len(S)-1):
    if S[i] == S[i+1]:
        counter += 1
         
    else:
        print((counter, int(S[i])), end=' ')
        counter=1

 

 

 

 

참조


 

itertools — Functions creating iterators for efficient looping

This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python. The module standardizes a core set...

docs.python.org

 

HackerRank Compress the String! solution in python

HackerRank Compress the String! solution in python 2, python 3, and pypy, pypy3 programming language with practical program code example explaination

programs.programmingoneonone.com