✅ Counter는 리스트, 문자열 등의 요소 개수를 쉽게 세는 도구이다.
✅ 중복된 요소의 개수를 빠르게 확인할 수 있다.
✅ 백준 10815, 10816 문제에서 Counter를 활용해 효율적인 풀이가 가능하다.
📌 Counter 객체란?
Counter는 collections 모듈에서 제공하는 계수기 도구이다.
리스트, 문자열 등의 요소 개수를 빠르게 세는 기능을 제공한다.
📌 사용법:
from collections import Counter
words = ['yun', 'Lee', 'yun', 'bang', 'Lee', 'Lee']
cnt = Counter(words)
print(cnt)
# Counter({'Lee': 3, 'yun': 2, 'bang': 1})
📌 Counter 예제
✅ 리스트에서 개수 세기
from collections import Counter
words = ['yun', 'Lee', 'yun', 'bang', 'Lee', 'Lee']
cnt = Counter(words)
print(cnt)
# Counter({'Lee': 3, 'yun': 2, 'bang': 1})
✅ 문자열에서 개수 세기
text = "yuneene shop"
cnt = Counter(text)
print(cnt)
# Counter({'e': 3, 'n': 2, 'y': 1, 'u': 1, ' ': 1, 's': 1, 'h': 1, 'o': 1, 'p': 1})
📌 Counter 주요 메서드
메서드 | 설명 |
most_common(n) | 가장 많이 등장한 요소 n개 반환 |
elements() | 요소를 개수만큼 반복하여 이터레이터로 반환 |
total() | 전체 요소 개수 반환 |
✅ most_common(n): 가장 많이 등장한 요소 반환
print(cnt.most_common(4))
# [('e', 3), ('n', 2), ('y', 1), ('u', 1)]
✅ elements(): 개수만큼 요소 반복
print(sorted(cnt.elements()))
# [' ', 'e', 'e', 'e', 'h', 'n', 'n', 'o', 'p', 's', 'u', 'y']
✅ total(): 전체 요소 개수 반환
print(cnt.total())
# 12
📌 Counter 활용 - 백준 문제 풀이
🔹 백준 10815번 - 숫자 카드
[문제 링크] 🔗 백준 10815번
💡 문제 설명
- N개의 숫자 카드를 가지고 있음.
- M개의 숫자가 주어졌을 때, 해당 숫자가 N개의 카드 중 있는지 확인해야 함.
- 숫자가 있으면 1, 없으면 0을 출력.
- Counter를 활용하면 빠르게 탐색 가능.
🔹 코드 구현
import sys
from collections import Counter
#입력값 받기
N = int(sys.stdin.readline().rstrip())
arrN = list(map(int, sys.stdin.readline().rsplit()))
M = int(sys.stdin.readline().rstrip())
arrM = list(map(int, sys.stdin.readline().rsplit()))
#Counter 객체로 개수 확인하여 문제풀이
cnt = Counter(arrN) # Counter({6: 1, 3: 1, 2: 1, 10: 1, -10: 1})
#print(cnt) #cnt 변수값을 확인
rtn = ""
# 결과 출력
for i in arrM:
if (i in cnt):
print(1, end=" ")
else:
print(0, end=" ")
🔹 실행 예제
입력
5
6 3 2 10 -10
8
10 9 -5 2 3 4 5 -10
출력
1 0 0 1 1 0 0 1
🔹 백준 10816번 - 숫자 카드 2
[문제 링크] 🔗 백준 10816번
💡 문제 설명
- N개의 숫자 카드를 가지고 있음.
- M개의 숫자가 주어졌을 때, 해당 숫자가 N개의 카드 중 몇 개 있는지 출력.
- Counter를 활용하면 빠르게 개수를 확인 가능.
🔹 코드 구현
import sys
from collections import Counter
#입력값 받기
N = int(sys.stdin.readline().rstrip())
arrN = list(map(int, sys.stdin.readline().rsplit()))
M = int(sys.stdin.readline().rstrip())
arrM = list(map(int, sys.stdin.readline().rsplit()))
#Counter 객체로 개수 확인
cnt = Counter(arrN) #Counter({10: 3, 3: 2, -10: 2, 6: 1, 2: 1, 7: 1})
# 결과 출력
for i in arrM:
if (i in cnt):
print(cnt[i],end=" ")
else:
print(0, end=" ")
🔹 실행 예제
입력
10
6 3 2 10 10 10 -10 -10 7 3
8
10 9 -5 2 3 4 5 -10
출력
3 0 0 1 2 0 0 2
📌 마무리 - 정리
✅ Counter는 리스트, 문자열 등의 요소 개수를 쉽게 셀 수 있는 도구
✅ Counter.most_common(n), Counter.elements(), Counter.total() 활용 가능
✅ 백준 10815번(숫자 카드) 문제에서 Counter를 사용해 탐색을 최적화
✅ 백준 10816번(숫자 카드 2) 문제에서 Counter로 개수를 빠르게 확인
'코딩라이브러리 > 파이썬' 카테고리의 다른 글
파이썬 스택, 큐 deque (with 백준 18258) (0) | 2024.05.30 |
---|---|
파이썬 중복제거 set 집합함수 (with 백준 2776) (0) | 2024.05.29 |
파이썬 람다 함수 lambda (with 백준 1181) (0) | 2024.05.27 |
파이썬 정렬 sort, sorted (with 백준 2750, 5597, 1181) (0) | 2024.05.24 |
파이썬 for while 조건문 (with 백준 2446, 2522) (2) | 2024.05.23 |