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

TIL - Algorithm - adjacent element

알고리즘 지뢰찾기 문제를 풀다가 배운 것

문제 출처: codesignal arcade intro 24

처음 접근은 반복문을 통해 현재 위치에서 +1 -1 해가며 주변에 지뢰가 있는지 확인했지만, 별도로 [-1, 0, 1] list를 loop에 넣어서 인근 element를 탐색하는 방법

1
2
for x in [-1, 0, 1]:
for y in [-1, 0, 1]: