문자열 split 및 반복 확인 코드
https://programmers.co.kr/learn/courses/30/lessons/60057
Tips.
1.일정 단위로 문자열 나누는 코드는 직접 짜기
2. return min(함수, for in)으로 짜보자
def short_str(s,n):
sub_word = [s[i:(i+n)] for i in range(0,len(s),n)]
short = []
previous, rep = sub_word[0], 1
for sw in sub_word[1:-1]:
if sw == previous:
rep += 1
else:
short.append(rep)
previous, rep = sw, 1
if sub_word[-1] == previous:
short.append(rep+1)
else:
short.append(rep)
return len("".join([str(sh) for sh in short if sh >1]))+(len(s)-(sum(short)-len(short))*n)
def solution(s):
short_len = [short_str(s,n) for n in range(1,int(len(s)/2)+1)]
return min(short_len) if short_len else 1
Tip.
for- if- else를 zip을 이용하여 간결하게 표기할 수 있다.
def short_str(s,n):
split_words = [s[i:(i+n)] for i in range(0,len(s),n)]
rep = []
for alpha,beta in zip([" "]+split_words,split_words+[" "]):
if alpha == beta:
rep[-1] += 1
else:
rep.append(0)
return len(s) - sum(rep)*n + len("".join([str(r+1) for r in rep if r > 0]))
return
def solution(s):
return min([short_str(s,n) for n in range(1,int(len(s)/2)+2)])