[백준] 4949: 균형잡힌 세상 - 파이썬[python]

다인·2024년 10월 5일

백준

목록 보기
73/112
post-thumbnail

아무리봐도 맞는 것 같은데 출력초과가 떠서 구글링해보니 sys.stdin.readline이 문제라더라. 시간 단축을 위해선 무조건 readline을 써야 한다고 생각했는데 아니었다. 그 이유를 추측해봤을 땐 아래와 같다.

출력초과 이유

  • readline과 input의 가장 큰 차이는 개행 문자(\n)이다.
  • 이 문제는 마지막 입력을 '.'으로 받는다.
  • 단순히 readline만 하면 입력은 '.\n'으로 저장하기 때문에 '.'일 때 while문이 끝나는 게 아니라 한 번 더 판단하고 yes를 출력하게 된다.
  • 그래서 개행문자를 제거해주어야 하는데, strip()이 아닌 rstip()을 해주어야 한다.
    strip()을 하게 되면 예제에서 ' .'입력이 '.'로 되어 이때 while문이 끝나버리기 때문이다.

input 사용

import sys

sentence = input()
while sentence != '.':
    sentence = list(sentence.split())
    stack = []

    for i in sentence:
        if i.isalpha():
            continue
        else:
            for j in i:
                if j == ')':
                    if stack and stack[-1] == '(':
                        stack.pop()
                    else:
                        stack.append(j)
                        break
                elif j == ']':
                    if stack and stack[-1] == '[':
                        stack.pop()
                    else:
                        stack.append(j)
                        break
                elif j == '(' or j == '[':
                    stack.append(j)
    if not stack:
        print("yes")
    else:
        print("no")
    sentence = input()
  • 나는 시간 단축을 위해 괄호가 들어있지 않은 단어이면 알파벳으로 이루어진 문자이므로 isalpha를 사용했다.
  • break문이 바로 바깥에 있어야지만 for-else가 먹는 건가..? ) 차례인데 스택이 비어있거나 맨 위가 (가 아닐 때 no를 출력하고 break 했더니 no가 두 번 출력되더라.. 그래서 그냥 스택이 비어있지 않게 하기 위해(=no를 출력하게 하기 위해) 스택에 j값을 집어넣었다.

readline 사용

import sys

sentence = sys.stdin.readline().rstrip()
while sentence != '.':
    sentence = list(sentence.split())
    stack = []

    for i in sentence:
        if i.isalpha():
            continue
        else:
            for j in i:
                if j == ')':
                    if stack and stack[-1] == '(':
                        stack.pop()
                    else:
                        stack.append(j)
                        break
                elif j == ']':
                    if stack and stack[-1] == '[':
                        stack.pop()
                    else:
                        stack.append(j)
                        break
                elif j == '(' or j == '[':
                    stack.append(j)
    if not stack:
        print("yes")
    else:
        print("no")
    sentence = sys.stdin.readline().rstrip()
  • 처음엔 readlines를 시도했다가 실패했당ㅎㅅㅎ
  • 예제로는 테스트할 때 잘 나오는데 제출하니까 틀렸습니다 뜸,. 모가 문젤까

0개의 댓글