[Python] input()대신 sys.stdin.readline()을 사용해보자

2021. 7. 24. 21:54Programming Language/.py

파이썬의 입출력 연산은 C나 C++과 같은 다른 언어에 비해 꽤 시간이 필요하다.

따라서, 시간을 절약하기위해 sys 모듈을 import해서 sys.stdin.readline()을 사용해보자.

 

아래의 예시를 IDLE에 입력해 실행해보자.

import sys
input = sys.stdin.readline()
print(input)
print("end")

 

위 이미지와 같이, 실행 결과 input 변수에는 문자열 형태로 인풋인 '123'이 개행문자 /n과 함께 저장된다.

따라서 출력 결과 또한, end와 input 사이에 빈 문자행이 위치한다.

 

위 예시처럼 개행문자를 받고싶지 않은 경우에는 .split()을 사용한다.

import sys
t = int(input())
while t > 0:
    a, b = map(int,sys.stdin.readline().split())
    print(a+b)
    t = t - 1

두 수를 입력받아 더해 출력하는 문제가 있다고 할 때 ( BOJ 15552번 )

a와 b를 입력받아 object안에 int형으로 데이터를 저장하고,

이를 프린트 출력한다.

 

여기서, a와 b를 할당할 때 map( )함수를 사용하는데 이 특성에 대해서 잘 알고 있어야 한다.

먼저 정의를 살펴보자.

map(function, iterable, ...)
Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list

여기서 주의해야할 점은 map함수가 반환하는 것은, iterable이라고 불리는 map object라는 점이다.

'Programming Language > .py' 카테고리의 다른 글

[백준] 2075번 : N번째 수 파이썬  (0) 2022.07.26
[Python] boj 10951 , A + B - 4  (0) 2021.05.13
[Python] 입출력과 사칙연산  (0) 2021.03.23