728x90
균형잡힌 세상
- 링크: https://www.acmicpc.net/problem/4949
- 난이도: 실버4
- 분류: 자료구조, 문자열, 스택
- 직접 푼 여부: O, but 출력초과 해결은 보고 함
- 언어: 파이썬
정답코드
import sys
while True:
# input
string = sys.stdin.readline().rstrip()
if string == "." or string == "./n": # "."만 해도 됨
break
# 초기화
stack = []
no = False
# print(string)
# 글자 하나 하나 보기
for s in string:
if s == "[" or s == "(":
stack.append(s)
elif s == "]":
if len(stack) == 0:
no = True
break
a = stack.pop()
if a != "[":
no = True
break
elif s == ")":
if len(stack) == 0:
no = True
break
a = stack.pop()
if a != "(":
no = True
break
if len(stack) != 0 or no:
print("no")
else:
print("yes")
근데 통과하기전에 계속 출력 초과가 났었다.
여기부턴 아직 의문인 곳이다.
이유는, sys.stdin.readline과 input이 입력값을 받아올 때 다르기 때문이라고 하는데, 이해가 잘 안된다.
sys.stdin.realine: \n도 받아옴 (개행문자도 받아옴)
input: \n은 빼고 받아옴
참고블로그:
https://velog.io/@rawoon/%EB%B0%B1%EC%A4%80-4949-%ED%8C%8C%EC%9D%B4%EC%8D%AC-sys.stdin.readline-%EC%B6%9C%EB%A0%A5%EC%B4%88%EA%B3%BC-%ED%95%B4%EA%B2%B0%EB%B0%A9%EB%B2%95%EA%B3%BC-%EC%9D%B4%EC%9C%A0
그래서 sys.stdinrealine().rsrtip()하니 문제개 해결되었는데, 그럼 rstrip()안하고 "." or ".\n"이렇게 하면 통과 되어야하는거 아닌가?
왜 아래와 같이 하면, 출력초과과 나는 것일까?
<통과안되는 코드>
import sys
while True:
# input
string = sys.stdin.readline()
if string =="." or string=="./n":
# print("end")
# print("yes")
end = True
break
# 초기화
stack =[]
no = False
# print(string)
# 글자 하나 하나 보기
for s in string:
if s=="[" or s=="(":
stack.append(s)
elif s=="]":
if len(stack)==0:
no = True
break
a = stack.pop()
if a!="[":
no = True
break
elif s==")":
if len(stack)==0:
no = True
break
a = stack.pop()
if a!="(":
no = True
break
if len(stack) !=0 or no:
print("no")
else:
print("yes")
<통과되는 코드>
import sys
while True:
# input
string = input()
if string == "." :
break
# 초기화
stack = []
no = False
# print(string)
# 글자 하나 하나 보기
for s in string:
if s == "[" or s == "(":
stack.append(s)
elif s == "]":
if len(stack) == 0:
no = True
break
a = stack.pop()
if a != "[":
no = True
break
elif s == ")":
if len(stack) == 0:
no = True
break
a = stack.pop()
if a != "(":
no = True
break
if len(stack) != 0 or no:
print("no")
else:
print("yes")
728x90
'취준! ✒ > LG' 카테고리의 다른 글
[LG전자] 코테준비 01. 무슨 문제 풀지 계획 세우기 (feat. 기출) (2) | 2023.10.23 |
---|---|
[AI과제분석 테스트] 1. 서론과 pandas -작성중 (1) | 2023.10.09 |