728x90
반응형
알고리즘 문제를 풀던 중 시간초과로 애를 먹고 있었다.
다른 분들의 풀이를 보니 input() 대신에 sys.stdin.readline()를 사용하여
시간초과를 해결 할 수 있다는 것을 알게 되었다.
우선 파이썬 공식 문서를 확인해보면
1. stdin is used for all interactive input (including calls to input());
2. stdout is used for the output of print() and > - expression statements and for the prompts of input();
3. The interpreter’s own prompts and its error messages go to stderr.
즉, input()은 raw_input()을 evaluate 한 결과를 반환하고 sys.stdin.readline()은 한 줄의 문자열을 반환한다.
그렇기 때문에 한 번에 읽어와 버퍼에 보관하고 사용자가 요구할 때
버퍼에서 읽어오는 sys.stdin이 input()보다 빠른 것이다.
앞으론 input() 대신에
sys.stdin.readline()
를 사용하는게 좋을 것 같다 ❗
예시)
import sys
n = int(sys.stdin.readline())
728x90
반응형
'Language > Python' 카테고리의 다른 글
[Python] for in 반복문, range, enumerate (0) | 2022.01.27 |
---|---|
예제) 사각형 넓이 구하기 (0) | 2021.04.02 |
네이버 뉴스 API 크롤링 (0) | 2021.03.28 |
댓글