# 공백으로 구분된 여러 데이터 입력받기
data = list(map(int, input().split()))
# 개수가 적은 경우 변수에 바로 할당
a, b, c = map(int, input().split())
입력 데이터가 많을 때 input() 대신 사용. 엔터가 줄 바꿈 기호로 포함되므로 rstrip() 필수!
import sys
data = sys.stdin.readline().rstrip()
print(data)
문자열 앞에 f를 붙이고 중괄호 안에 변수명을 넣어 간편하게 출력
answer = 7
print(f"정답은 {answer}입니다.")
리스트, 튜플, 문자열, 딕셔너리 모두에서 사용 가능
a = [1, 2, 3]
print(3 in a) # True
print(5 not in a) # True
score = 85
result = "Success" if score >= 80 else "Fail"
print(result) # Success
함수 내부에서 외부 변수를 직접 참조할 때 사용
a = 0
def func():
global a
a += 1
for i in range(10):
func()
print(a) # 10
파이썬 함수는 여러 값을 동시에 반환할 수 있다 (튜플로 반환됨)
def operator(a, b):
return a + b, a - b, a * b, a / b
a, b, c, d = operator(7, 3)
print(a, b, c, d) # 10 4 21 2.333...
함수를 한 줄로 간결하게 표현
# 일반 함수
def add(a, b):
return a + b
# 람다 표현식
print((lambda a, b: a + b)(3, 7)) # 10
array = [('홍길동', 50), ('이순신', 32), ('아무개', 74)]
# 두 번째 원소(점수)를 기준으로 정렬
print(sorted(array, key=lambda x: x[1]))
# [('이순신', 32), ('홍길동', 50), ('아무개', 74)]
list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]
result = list(map(lambda a, b: a + b, list1, list2))
print(result) # [7, 9, 11, 13, 15]
# sum() - 합계
print(sum([1, 2, 3, 4, 5])) # 15
# min(), max() - 최솟값, 최댓값
print(min(7, 3, 5, 2)) # 2
print(max(7, 3, 5, 2)) # 7
# eval() - 문자열 수식 계산
print(eval("(3+5)*7")) # 56
# sorted() - 정렬 (원본 변경 없음)
print(sorted([9, 1, 8, 5, 4])) # [1, 4, 5, 8, 9]
print(sorted([9, 1, 8, 5, 4], reverse=True)) # [9, 8, 5, 4, 1]
# sorted() with key
array = [('홍길동', 35), ('이순신', 75), ('아무개', 50)]
result = sorted(array, key=lambda x: x[1], reverse=True)
print(result)
# [('이순신', 75), ('아무개', 50), ('홍길동', 35)]
| 라이브러리 | 주요 기능 |
|---|---|
itertools | 순열, 조합 등 반복 데이터 처리 |
heapq | 힙(우선순위 큐) 구현 |
bisect | 이진 탐색 |
collections | deque, Counter 등 유용한 자료구조 |
math | 팩토리얼, 제곱근, GCD, 삼각함수, 상수 등 |
| 종류 | 공식 | 함수 |
|---|---|---|
| 순열 | nPr | permutations(data, r) |
| 조합 | nCr | combinations(data, r) |
| 중복 순열 | n^r | product(data, repeat=r) |
| 중복 조합 | nHr | combinations_with_replacement(data, r) |
from itertools import permutations
data = ['A', 'B', 'C']
result = list(permutations(data, 3))
print(result)
# [('A','B','C'), ('A','C','B'), ('B','A','C'),
# ('B','C','A'), ('C','A','B'), ('C','B','A')]
from itertools import combinations
data = ['A', 'B', 'C']
result = list(combinations(data, 2))
print(result)
# [('A', 'B'), ('A', 'C'), ('B', 'C')]
from itertools import product
data = ['A', 'B', 'C']
result = list(product(data, repeat=2))
print(result)
# [('A','A'), ('A','B'), ('A','C'),
# ('B','A'), ('B','B'), ('B','C'),
# ('C','A'), ('C','B'), ('C','C')]
from itertools import combinations_with_replacement
data = ['A', 'B', 'C']
result = list(combinations_with_replacement(data, 2))
print(result)
# [('A','A'), ('A','B'), ('A','C'),
# ('B','B'), ('B','C'), ('C','C')]
리스트 내 원소의 등장 횟수를 자동으로 카운팅
from collections import Counter
counter = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
print(counter['blue']) # 3
print(counter['green']) # 1
print(dict(counter)) # {'red': 2, 'blue': 3, 'green': 1}
import math
def lcm(a, b):
return a * b // math.gcd(a, b)
a, b = 21, 14
print(math.gcd(a, b)) # 최대공약수(GCD): 7
print(math.lcm(a, b)) # 최소공배수(LCM): 42
💡 Python 3.9부터는
math.lcm(a, b)로 바로 사용 가능!