enumerate() 함수는 리스트(또는 튜플, 문자열 등)를 반복문에서 사용할 때, 인덱스(순서)와 값(요소)을 동시에 꺼내주는 매우 유용한 내장 함수.
enumerate()는 (인덱스, 값) 형태의 튜플을 반환하므로, 반복문 for에서 변수 두 개로 받아서 사용하면 편리.
fruits = ['apple', 'banana', 'orange']
# 인덱스(i)와 값(fruit)을 동시에 가져옴
for i, fruit in enumerate(fruits):
print(i, fruit)
실행 결과:
0 apple
1 banana
2 orange
start 옵션)기본적으로 인덱스는 0부터 시작하지만, start 매개변수를 사용하면 시작 숫자를 바꿀 수 있습니다. 순위(1등, 2등...)를 매길 때 유용.
fruits = ['apple', 'banana', 'orange']
# 1번부터 시작하도록 설정
for i, fruit in enumerate(fruits, start=1):
print(f"{i}등: {fruit}")
실행 결과:
1등: apple
2등: banana
3등: orange
리스트를 {인덱스: 값} 형태의 딕셔너리로 만들고 싶을 때도 사용할 수 있음.
fruits = ['apple', 'banana', 'orange']
fruit_dict = dict(enumerate(fruits))
print(fruit_dict)
# {0: 'apple', 1: 'banana', 2: 'orange'}
for i in range(len(list)): 대신 enumerate를 쓰면 코드가 훨씬 깔끔.enumerate를 사용.파이썬은 문자열로 된 수식을 eval() 함수로 직접 계산할 수 있습니다.
s = '1**1+2**2+3**3'
result = eval(s)
print(result) # 30 (1^1 + 2^2 + 3^3 = 1 + 4 + 27)
# 단계별 계산 확인
print(1**1) # 1
print(2**2) # 4
print(3**3) # 27
eval() 설명:
+, -, *, /), 제곱(**), 괄호 등 모두 지원안전한 대안:
# sympy 라이브러리 사용 (권장)
from sympy import sympify
s = '1**1+2**2+3**3'
result = sympify(s).evalf()
print(result) # 30.0
파이썬에서 정규식을 사용하려면 import re를 먼저 해야 합니다.
import re
s = '1S*2D*3T'
re.findall(패턴, 문자열): 모든 매치 결과 리스트 반환# 숫자만 추출
numbers = re.findall(r'\d', s) # ['1', '2', '3']
# 숫자 + 그 뒤 문자들 (당신이 원하는 결과)
parts = re.findall(r'\d[^0-9]*', s) # ['1S*', '2D*', '3T']
re.search(패턴, 문자열): 첫 번째 매치 결과match = re.search(r'\dS\*', s)
print(match.group()) # '1S*'
re.match(패턴, 문자열): 맨 처음부터 매치match = re.match(r'\d', s) # 처음이 숫자인지 확인
print(match.group()) # '1'
| 패턴 | 의미 | 예제 |
|---|---|---|
\d | 0-9 숫자 하나 | r'\d' → ['1','2','3'] |
\D | 숫자가 아닌 문자 | r'\D' → ['S','*','D','*','T'] |
. | 어떤 문자 하나 | r'.' → 모든 한 글자 |
* | 앞 문자 0번 이상 반복 | r'\d*' → ['','','1','','2','','3',''] |
[^0-9]* | 숫자가 아닌 문자 0번 이상 | 숫자 다음 비숫자들 |
import re
s = '1S*2D*3T'
# 방법 1: 숫자 + 그 뒤 모든 비숫자
result = re.findall(r'\d[^0-9]*', s)
print(result) # ['1S*', '2D*', '3T']
# 방법 2: 숫자 + 문자 + * 패턴
result = re.findall(r'\d[A-Z]\*', s)
print(result) # ['1S*', '2D*']
s = "가격: 1,234원, 수량: 5개"
# 숫자만
print(re.findall(r'\d+', s)) # ['1234', '5']
# 전화번호
phone = "010-1234-5678"
print(re.findall(r'\d{3}-\d{4}-\d{4}', phone)) # ['010-1234-5678']
핵심: r'패턴'에서 r은 raw string을 의미해서 백슬래시(\)를 이스케이프 처리 안 해도 됩니다!
Counter는 파이썬의 collections 모듈에 들어 있는 클래스입니다.
리스트나 문자열 같은 이터러블(iterable)의 원소 개수를 자동으로 세어주는 딕셔너리입니다.
from collections import Counter
Counter(데이터)
👉 결과는 {원소: 개수} 형태의 딕셔너리처럼 동작합니다.
from collections import Counter
arr = ["a", "b", "a", "c", "b", "a"]
count = Counter(arr)
print(count)
결과:
Counter({'a': 3, 'b': 2, 'c': 1})
Counter("banana")
결과:
Counter({'a': 3, 'n': 2, 'b': 1})
👉 문자 하나하나를 자동으로 셉니다.
count["a"]
👉 "a"의 개수 반환
(없는 값은 0 반환 — 에러 안 남 👍)
count.most_common()
결과:
[('a', 3), ('b', 2), ('c', 1)]
count.most_common(1)
결과:
[('a', 3)]
Counter("aab") + Counter("bbc")
결과:
Counter({'b': 3, 'a': 2, 'c': 1})
👉 개수끼리 더함
Counter("aab") - Counter("ab")
결과:
Counter({'a': 1})
👉 음수는 자동 제거
Counter("aab") & Counter("abb")
결과:
Counter({'a': 1, 'b': 1})
👉 최소값 기준
Counter("aab") | Counter("abb")
결과:
Counter({'a': 2, 'b': 2})
👉 최대값 기준
| 일반 dict | Counter |
|---|---|
| 키가 없으면 KeyError | 키가 없으면 0 |
| 직접 개수 증가 필요 | 자동 카운트 |
| 연산 기능 없음 | +, -, &, |
✔ 빈도수 계산
✔ 최빈값 찾기
✔ 동명이인 처리
✔ 문자열 분석
✔ 해시 기반 문제 풀이
permutations는 코딩테스트에서 정말 자주 나오는 핵심 도구라서, 한 번 제대로 정리해두면 계속 써먹을 수 있어요 👍
파이썬의 itertools 모듈에 포함된 함수입니다.
👉 순열 = 순서가 있는 경우의 수
from itertools import permutations
permutations(iterable, r)
iterable: 리스트, 문자열 등r: 뽑을 개수 (생략 시 전체 길이)from itertools import permutations
arr = [1, 2, 3]
result = list(permutations(arr, 2))
print(result)
결과:
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
👉 순서가 다르면 다른 경우로 취급
from itertools import permutations
result = list(permutations("abc", 2))
결과:
[('a','b'), ('a','c'), ('b','a'), ...]
list(permutations([1,2,3]))
결과:
[(1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2), (3,2,1)]
👉 3! = 6개
from itertools import permutations
for p in permutations("123", 2):
print(''.join(p))
출력:
12
13
21
23
31
32
s = "011"
result = set()
for p in permutations(s):
result.add(int(''.join(p)))
print(result)
👉 "011" → 중복 발생 → set으로 제거
from itertools import permutations
s = "173"
result = set()
for i in range(1, len(s)+1):
for p in permutations(s, i):
result.add(int(''.join(p)))
print(result)
👉 모든 자리수 조합 생성
n! / (n-r)!n!👉 n이 커지면 매우 빠르게 폭발 ⚠️
(1,2) # 리스트 아님
permutations(arr, 2)
👉 바로 list로 감싸거나 반복문 사용
permutations("011")
👉 같은 값 여러 번 나옴
| 구분 | permutations | combinations |
|---|---|---|
| 순서 | 중요 | 중요 X |
| 예 | (1,2) ≠ (2,1) | (1,2) = (2,1) |
✔ 모든 경우의 수 탐색
✔ 문자열 재배열
✔ 숫자 조합 생성
✔ 브루트포스 문제
👉 “순서까지 고려한 경우의 수 = permutations”