레슨 1 · 파이썬 알고리즘 기초
파이썬에서 입력을 받을 때는 input() 함수를 사용해요.
알고리즘 문제를 풀 때 입력 형태가 다양하므로 패턴을 익혀두세요.
a = input()입력 예시:
mjacademy
a, b = input().split() # "mj academy" → 공백 기준
a, b = input().split(',') # "mj,academy" → 쉼표 기준
a, b, c = input().split() # "mj aca demy"
arr = list(input().split()) # 개수 모를 때 → 리스트로입력 예시:
mj academy
mj,academy
mj aca demy
m j a c a d e m y
a = int(input()) # 정수
a = float(input()) # 실수입력 예시:
2000
20.5
a, b, c = map(int, input().split()) # "1 2 3" → 공백 기준
a, b, c = map(int, input().split(',')) # "1,2,3" → 쉼표 기준입력 예시:
1 2 3
1,2,3
map(int, ...)= 각 원소를 int로 변환해주는 함수예요.
arr = list(map(int, input().split()))입력 예시:
1 2 3 4 5 6 7
결과: arr = [1, 2, 3, 4, 5, 6, 7]
n = int(input())
arr = [int(input()) for _ in range(n)]입력 예시:
5
1
2
3
4
5
결과: arr = [1, 2, 3, 4, 5]
n = int(input())
arr = [list(map(int, input().split())) for _ in range(n)]입력 예시:
5
1 2 3
2 2 3
3 2 5
4 3 5
5 1 2
결과: arr = [[1,2,3], [2,2,3], [3,2,5], [4,3,5], [5,1,2]]
a, b = input().split() # 일단 문자열로 받고
b = int(b) # 숫자만 변환입력 예시:
mjacademy 1
| 입력 형태 | 코드 |
|---|---|
| 문자열 1개 | a = input() |
| 숫자 1개 | a = int(input()) |
| 공백 구분 여러 숫자 | a, b = map(int, input().split()) |
| 가로 리스트 | arr = list(map(int, input().split())) |
| 세로 리스트 | arr = [int(input()) for _ in range(n)] |
| 2차원 리스트 | arr = [list(map(int, input().split())) for _ in range(n)] |
💡 알고리즘 문제에서
sys.stdin.readline을 써야 빠른 경우가 많아요. 다음 레슨 '빠른 입출력'에서 배워요!