백준 10820 (문자열 분석) - Python

김종언·2024년 3월 13일
0

백준

목록 보기
16/18

문제

import sys

cnt = [0] * 4


while True:
    try:
        S = sys.stdin.readline().strip()
        for i in S:
            if i.islower():
                cnt[0] += 1
            elif i.isupper():
                cnt[1] += 1
            elif i.isdigit():
                cnt[2] += 1
            else:
                cnt[3] += 1
        print(cnt[0], cnt[1], cnt[2], cnt[3])
        cnt = [0] * 4
    except EOFError:
        break

내 코드는 이러했다. 소문자, 대문자, 숫자, 공백을 cnt라는 배열에서 세는 방법을 선택했다. islower(), isupper(), isdigit() 메소드를 이용해서 종류를 구분하고 해당되는 위치에 1을 더해줬다.

근데 보통 테스트케이스를 먼저 입력해주고 시작하는데, 이 문제는 그렇지 않았다. 조금 당황했지만 구글링했다.

import sys

while True:
    line = sys.stdin.readline().rstrip('\n')

    if not line:
        break

    # 소문자, 대문자, 숫자, 공백
    l, u, d, s = 0, 0, 0, 0
    for each in line:
        if each.islower():
            l += 1
        elif each.isupper():
            u += 1
        elif each.isdigit():
            d += 1
        elif each.isspace():
            s += 1

    print(l, u, d, s)

보완된 코드이다. 입력받지 않았을 때 break해주는 구문을 만들면 무한루프가 해결된다.

또 cnt 배열을 만들었던 나와 달리 각각 값을 정해줬다. 이건 장단점이 있겠지만 조금 더 단순하고 직관적이여 보인다.

profile
나는 김종언이다.

0개의 댓글