본문으로 바로가기

[ BAEKJOON ONLINE JUDGE ]

15552 빠른 A+B _ Python 파이썬

 

 

" 문제  : 백준 15552 빠른 A+B "

 

www.acmicpc.net/problem/15552

 

15552번: 빠른 A+B

첫 줄에 테스트케이스의 개수 T가 주어진다. T는 최대 1,000,000이다. 다음 T줄에는 각각 두 정수 A와 B가 주어진다. A와 B는 1 이상, 1,000 이하이다.

www.acmicpc.net

 




" 아이디어 "

 

 

' 본격적으로 for문 문제를 풀기 전에 주의해야 할 점이 있다. 입출력 방식이 느리면 여러 줄을 입력받거나 출력할 때 시간초과가 날 수 있다는 점이다. ---중략 ---  Python을 사용하고 있다면, input 대신 sys.stdin.readline을 사용할 수 있다. 단, 이때는 맨 끝의 개행문자까지 같이 입력받기 때문에 문자열을 저장하고 싶을 경우 .rstrip()을 추가로 해 주는 것이 좋다. '

 

문제만 잘 읽어보고 따라하면 풀 수 있다.

간단하게 말하면 잦은 입출력을 반복할 때에는 input() 보다 readline()을 사용하는 것이 더 효율적이라는 아이디어다.

단순히 성능이 좋기도 하지만 사용하는 데 있어서도 신경써야 할 차이가 있어서 정리해둔다.

 

 

# input() vs readline()

 

input() sys.stdin.readline()

 - input 은 개행문자를 받지 않는다

 (The input takes input from the user but does not read escape character)

 - 입력을 받기 전에 프롬프트를 띄운다

 (It has a prompt that represents the default value before the user input)


 - readline은 개행문자의 입력도 받는다

 (The readline() also takes input from the user but also reads the escape character)

 - parameter로 사이즈를 받아서 읽을 byte 수를 지정할 수 있다 (음수가 아닌 수) 

 (Readline has a parameter named size, Which is a non-negative number, it actually defines the bytes to be read)
import sys

# 여러 줄을 입력 받을 때
words = [sys.stdin.readline() for i in range(n)]

# 여러 문자를 int형으로 바로 저장하고 싶을 때
a, b = map(int, sys.stdin.readline().split())

# 여러 문자를 int형을 담은 list로 저장하고 싶을 때
word_list = list(map(int, sys.stdin.readline().split()))

 

 




" 코드 "

 

 

앞서 input 과 readline의 차이점이 장황했지만 문제 자체는 성능차이에 중점을 둔 것이기 때문에

입력을 모두 readline으로 받으면 해결된다.

input으로 받을 시 시간초과가 발생한다.

 

1
2
3
4
5
6
import sys
input = sys.stdin.readline
= int(input())
for i in range(t):
  x, y = map(int, input().split())
  print(x + y)
cs

 

 




" 참고자료 "

 

 

docs.python.org/3/library/sys.html

 

sys — System-specific parameters and functions — Python 3.9.1 documentation

sys — System-specific parameters and functions This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available. sys.abiflags On POSIX systems where P

docs.python.org

 

www.geeksforgeeks.org/difference-between-input-and-sys-stdin-readline/

 

Difference between input() and sys.stdin.readline() - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

반응형