TIL - Python itertools groupby 활용

CodeSignal이라는 알고리즘 문제 풀이 사이트에서 문제에서 정해준 규칙으로 문자열을 변경하는 Line Encoding이라는 문제를 푸는데..

규칙은 아래와 같았습니다.

  • First, the string is divided into the least possible number of disjoint substrings consisting of identical characters
    • for example, "aabbbc" is divided into ["aa", "bbb", "c"]
  • Next, each substring with length greater than one is replaced with a concatenation of its length and the repeating character
    • for example, substring "bbb" is replaced by "3b"
  • Finally, all the new strings are concatenated together in the same order and a new string is returned.

예시

For s = "aabbbc", the output should be
lineEncoding(s) = "2a3bc".

조금 무식하게 풀긴 풀었는데.. 풀고나서 다른 문제풀이들을 보니 itertools 모듈의 groupby를 활용해서 간단하게 푸는 것을 볼 수 있었습니다.

‘aabbbc’라는 문자열이 있을 때 아래와 같이 활용 가능합니다.

1
2
3
4
from itertools import groupby

for k, g in groupby(input_string):
print(k, list(g), len((list(g))))
1
2
3
'a' ['a', 'a'] 2
'b' ['b', 'b', 'b'] 3
'c' ['c'] 1

Python - json.loads()와 json.dumps()의 차이

JSON (JavaScript Object Notation)

json object는 key value pair로 이루어지고 { } 중괄호에 의해 둘러쌓여있습니다.

json.loads()

  • json.loads()는 문자열을 받아서 json object를 return합니다.

json.dumps()

  • json.dumps()는 json object를 받아서 문자열을 return 합니다.

json

TIL - Pyhton 'list' object has no attribute 'split'

구글링하면서 임기응변식으로 Python을 사용하고 학습하게 되었을 때 이런 부분들에서 약점이 생기는 것 같습니다.

위 제목의 에러가 발생하게 된 원인은 list에 split 메소드를 사용했기 때문인데, split 메소를 어떻게 써야하는지 document를 보면서 짚고 넘어가려고 합니다.

Error Message

1
'list' object has no attribute 'split'

Document

str split

첫 문구에 string의 word를 list형태로 return해준다고 나와있습니다. 즉, list에 직접 split 메소드를 쓸 수 없고 list안에 있는 문자열을 순회하면서 사용하면 됩니다.