본문 바로가기
개인공부/Python

[Python] Input vs. sys.stdin.readline 차이점?

by BuyAndPray 2020. 10. 2.
반응형

Python으로 백준 문제를 풀 때 내장 함수 input()으로 입력을 받으면 시간 초과로 오답처리가 되고, sys 모듈의sys.stdin.readline()으로 입력을 받으면 시간 안에 채점이 되는 경우가 자주 발생한다. 왜 그런지 한 번 알아보자.

 

Python 2.x

일단 Python 2.x 버전에서는 사용자 입력을 처리하기 위한 내장 함수로 input()과 raw_input()이 있다. 이 둘의 차이점은 raw_input()은 입력 값을 무조건 문자열로 받는 반면, input()은 입력으로 들어온 값을 evaluate 해서 그 값에 맞는 자료형으로 초기화한다. 

 

아래 예를 보면 숫자 10을 입력했을 때는 integer type이지만, "python"을 입력했을 때는 string type으로 결과가 나오게 된다. 여기서 주의할 점은 ""를 제외한 그냥 python만 입력할 경우 stringInput이 python이라는 이름을 가진 변수로 인식되기 때문에, 이 경우는 에러가 뜨게 된다.

 

# Python 2.7
# input()

intInput = input("Integer input : ")
print(type(intInput))

stringInput = input("String input : ")
print(type(stringInput))
# 결과
Integer input : 10
<type 'int'>
String input : "python"
<type 'str'>

 

반면에 raw_input()은 입력 값을 무조건 문자열로 받는다. 따라서 이 경우는 ""도 필요하지 않다.

# Python 2.7
# raw_input()

intInput = raw_input("Integer input : ")
print(type(intInput))

stringInput = raw_input("String input : ")
print(type(stringInput))
# 결과
Integer input : 10
<type 'str'>
String input : python
<type 'str'>

이처럼 Python 2.x 에서 input()은 입력으로 들어온 값을 evaluation 하고 변수에 저장하기 때문에 raw_input()에 비해 상대적으로 느리게 된다.

 

Python 3.x

하지만 Python 3.x로 넘어옴에 따라서 raw_input() 함수는 사라지고, input()이 raw_input()의 역할을 하게 된다. 따라서 Python 3.x에서 input()도 결과적으로 입력 값을 문자열로 받게 된다. 그리고 Python 3.x로 넘어오면서 모든 변수가 객체(object)로 처리됨에 따라서 결과 값도 type에서 class로 바뀌게 되었다.

# Python 3.7
# input()

intInput = input("Integer input : ")
print(type(intInput))

stringInput = input("String input : ")
print(type(stringInput))
# 결과
Integer input : 10
<class 'str'>
String input : python
<class 'str'>

그렇다면 도대체 input()은 왜 느릴까?

 

input과 sys.stdin.readline의 차이점

일단 sys.stdin.readline()과 input()은 같은 역할을 하지 않는다.

 

input() 내장 함수는 parameter로 prompt message를 받을 수 있다. 따라서 입력받기 전 prompt message를 출력해야 한다. 물론 prompt message가 없는 경우도 있지만, 이 경우도 약간의 부하로 작용할 수 있다. 하지만, sys.stdin.readline()은 prompt message를 인수로 받지 않는다.

 

또한, input() 내장 함수는 입력받은 값의 개행 문자를 삭제시켜서 리턴한다. 즉 입력받은 문자열에 rstrip() 함수를 적용시켜서 리턴한다. 반면에 sys.stdin.readline()은 개행 문자를 포함한 값을 리턴한다. 이 때문에 조금 귀찮은 점이 있기도 하다.

 

결론

결론적으로 input() 내장 함수는 sys.stdin.readline()과 비교해서 prompt message를 출력하고, 개행 문자를 삭제한 값을 리턴하기 때문에 느리다.

 

따라서 백준에서 Python으로 문제를 풀 때는 아래와 같이 sys.stdin.readline()을 활용해서 입력을 받는 것이 좋다.

# Python 3.7
# sys.stdin.readline()

import sys

a = sys.stdin.readline().strip()

print("Input :", a)
# 결과
1 2 3 4 5
Input : 1 2 3 4 5
반응형

'개인공부 > Python' 카테고리의 다른 글

[Python] 정규표현식 완전정복!  (1) 2020.12.07
[Python] heapq 모듈 사용법  (0) 2020.10.30
[Python] Mutable vs. Immutable 차이점?  (0) 2020.09.29

댓글