[이코테] 파이썬 문법 정리(2)

김우진·2026년 4월 2일

알고리즘

목록 보기
2/4

파이썬 문법 정리 - 입출력, 함수, 표준 라이브러리

📥 입력 방법

기본 입력 - map()

# 공백으로 구분된 여러 데이터 입력받기
data = list(map(int, input().split()))

# 개수가 적은 경우 변수에 바로 할당
a, b, c = map(int, input().split())

빠른 입력 - sys.stdin.readline()

입력 데이터가 많을 때 input() 대신 사용. 엔터가 줄 바꿈 기호로 포함되므로 rstrip() 필수!

import sys

data = sys.stdin.readline().rstrip()
print(data)

🖨️ 출력 방법

f-string (Python 3.6+)

문자열 앞에 f를 붙이고 중괄호 안에 변수명을 넣어 간편하게 출력

answer = 7
print(f"정답은 {answer}입니다.")

🔧 유용한 문법

in / not in 연산자

리스트, 튜플, 문자열, 딕셔너리 모두에서 사용 가능

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

global 키워드

함수 내부에서 외부 변수를 직접 참조할 때 사용

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...

⚡ 람다 표현식 (Lambda)

함수를 한 줄로 간결하게 표현

# 일반 함수
def add(a, b):
    return a + b

# 람다 표현식
print((lambda a, b: a + b)(3, 7))  # 10

sorted()와 함께 사용

array = [('홍길동', 50), ('이순신', 32), ('아무개', 74)]

# 두 번째 원소(점수)를 기준으로 정렬
print(sorted(array, key=lambda x: x[1]))
# [('이순신', 32), ('홍길동', 50), ('아무개', 74)]

map()과 함께 여러 리스트에 적용

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이진 탐색
collectionsdeque, Counter 등 유용한 자료구조
math팩토리얼, 제곱근, GCD, 삼각함수, 상수 등

🔀 순열과 조합 (itertools)

종류공식함수
순열nPrpermutations(data, r)
조합nCrcombinations(data, r)
중복 순열n^rproduct(data, repeat=r)
중복 조합nHrcombinations_with_replacement(data, r)

순열 (permutations)

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')]

조합 (combinations)

from itertools import combinations

data = ['A', 'B', 'C']
result = list(combinations(data, 2))
print(result)
# [('A', 'B'), ('A', 'C'), ('B', 'C')]

중복 순열 (product)

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')]

중복 조합 (combinations_with_replacement)

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')]

🧮 collections - Counter

리스트 내 원소의 등장 횟수를 자동으로 카운팅

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}

➗ math - 최대공약수 & 최소공배수

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)로 바로 사용 가능!

0개의 댓글