파이썬에서는 보통 문자를 입력 받을 때 imput() 으로 문자열 값을 입력받는다. 하지만 반복문등으로 여러 줄을 입력받아야 할 때는 시간 초과문제를 잦게 볼 수 있다.
그렇게 때문에 파이썬에서 제공하는 입출력 라이브러리 import sys 를 불러오고 sys.stdin.readline() 을 사용하면 좋다.
n = input('문자를 입력하세요 :')
import sys
n = sys.stdin.readline()
문자열의 맨 앞, 맨 뒤의 공백을 제거해준다.
.rstrip() 은 오른쪽, .lstrip() 은 왼쪽에서 공백을 제거해준다.
import sys
a = sys.stdin.readline()
print('hello : ', a.strip())
print('python')
입력 : a
>>>hello : a
python
import sys
a = sys.stdin.readline()
print('hello : ', a)
print('python')
입력 : a
>>> hello : a
python
import sys
n = int(sys.stdin.readline())
n = "hello python"
n.split()
>> ['hello', 'python']
map() 은 반복 가능한 객체(리스트 등)에 대해 각각의 요소들을 지정된 함수로 처리해주는 기능을 가진 함수이다.
다음과 같이 사용할 경우 a,b,c 에 대해 각각 int 형으로 형변환이 가능하다.
import sys
a,b,c = map(int,sys.stdin.readline().split())
print(a,b,c)
입력 : 10,20,30
>>> 10 20 30
import sys
data = list(map(int,sys.stdin.readline().split()))
import sys
data = []
n = int(sys.stdin.readline())
for i in range(n):
data.append(list(map(int,sys.stdin.readline().split())))
그렇다면 왜 두 개의 속도 차이가 나는 원인은 무엇일까?