![[백준 / BOJ] 1000번 A+B (C++, Python) (부제 : map(int, input().split())에 대하여)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FcndDi5%2FbtrK48FySPV%2Fz4RZSdZ8kae8PsvnK3P8P1%2Fimg.jpg)
[백준 / BOJ] 1000번 A+B (C++, Python) (부제 : map(int, input().split())에 대하여)◎ 자료구조와 알고리즘/백준(BOJ) 문제풀이2022. 8. 31. 20:52
Table of Contents
반응형
링크 : https://www.acmicpc.net/problem/1000
1000번: A+B
두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
www.acmicpc.net
문제

문제 풀이
간단한 연산 문제다.
C++ 상세 풀이
C++ 풀이 펼쳐보기
별로 특별하게 생각할 것 없이 두 수를 입력받은 후 더해주면 된다.
#include <iostream>
void init() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
}
int main() {
init();
int A, B;
std::cin >> A >> B;
std::cout << A + B;
return 0;
}
Python 상세 풀이 (map(int, input().split())은 정확히 어떻게 작동할까?)
Python 풀이 펼쳐보기
코드 줄 자체는 짧지만 조금만 더 깊이 파헤쳐보자.
if __name__ == "__main__":
A, B = map(int, input().split())
print(A + B)
map함수의 원형은 map(function, iterable [, …])으로 이루어져 있는데, 이는 반복 가능한 자료형을 어떠한 함수를 거치도록 해 그 함수가 적용된 또 다른 반복 가능한 자료형을 만들어주는 함수이다.
이는 곧 input().split()을 통해 받은 문자열을 int 함수를 거쳐 int형 map 객체로 변환하라는 뜻이다. 아래 예제를 보자.
if __name__ == "__main__":
A = map(int, input().split())
print(A)
print([*A])
[결과]
<map object at 0x000001ECF76175B0>
[3, 1]
3, 1을 입력하고 이를 만약 하나의 변수에만 입력받는다면 A는 map 객체로 선언되고, 이를 언패킹 후 리스트로 변환해 실행하면 [3, 1]이 출력되는 것을 볼 수 있다.
그런데 변수를 배정한 만큼 입력값을 받으면 파이썬이 자동으로 배정된 변수에 값을 순서대로 삽입한다.
따라서 문제에서는 최종적으로 A + B를 출력하는 것 만으로 답을 구할 수 있다.
코드 전문
C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
void init() { | |
std::ios_base::sync_with_stdio(false); | |
std::cin.tie(nullptr); | |
std::cout.tie(nullptr); | |
} | |
int main() { | |
init(); | |
int A, B; | |
std::cin >> A >> B; | |
std::cout << A + B; | |
return 0; | |
} |
Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if __name__ == "__main__": | |
A, B = map(int, input().split()) | |
print(A + B) |
소감
C++에서는 간단하지만 파이썬에서는 map(int, input().split())을 자세히 파헤쳐볼 기회를 준 문제였다.
반응형
'◎ 자료구조와 알고리즘 > 백준(BOJ) 문제풀이' 카테고리의 다른 글
[백준 / BOJ] 10998번 AxB (C++, Python) (0) | 2022.09.01 |
---|---|
[백준 / BOJ] 1001번 A-B (C++, Python) (0) | 2022.09.01 |
[백준 / BOJ] 10718번 We love kriii (C++, Python) (0) | 2022.08.30 |
[백준 / BOJ] 2557번 Hello World (C++, Python) (부제 : Python print에 대해) (0) | 2022.08.29 |
[백준 / BOJ] 9184번 신나는 함수 실행 (C++, Python) (0) | 2022.08.12 |
@Reo :: 코드 아카이브
자기계발 블로그