점프 투 파이썬 종합문제 Q14 문자열 압축하기
def compress_string(s):
    _c = ""
    cnt = 0
    result = ""
    for c in s:
        if c!=_c:
            _c = c
            if cnt: result += str(cnt)
            result += c
            cnt = 1
        else:
            cnt +=1
    if cnt: result += str(cnt)
    return result

print (compress_string("aaaabbcccccca")) 

==============================================
위 코드에서

if cnt: result += str(cnt)
result +=c

로 입력을 하면, a4b2c6a로 출력이 되고

if cnt: 
    result += str(cnt)
    result += c

로 입력을 하면, 3b2c6a 로 출력이 되는데
왜그런걸까요..ㅜ

sujin87.lee 418

M 2020년 8월 10일 9:54 오전

목록으로
1개의 답변이 있습니다. 1 / 1 Page
if cnt: result += str(cnt)
result +=c

위의 경우는 if 문 밖에서 result+=c 가 실행되고

if cnt: 
    result += str(cnt)
    result += c

위의 경우는 if 문 안에서 result+=c 가 실행됩니다.

박응용

2020년 8월 10일 9:55 오전