코딩라이브러리/파이썬

파이썬 Counter (with 백준 10815, 10816)

유니네 라이브러리 2024. 5. 28. 19:54

Counter() 객체

  • 편리하고 빠르게 개수를 세도록 지원하는 계수기 도구 제공
  • collections 모듈의 Counter() 객체 선언하여 사용한다.
    ex) from collections import Counter
from collections import Counter
cnt = Counter()
for word in ['yun', 'Lee', 'yun', 'bang', 'Lee', 'Lee']:
    cnt[word] += 1
print(cnt) # Counter({'Lee': 3, 'yun': 2, 'bang': 1})

words = ['yun', 'Lee', 'yun', 'bang', 'Lee', 'Lee']
cnt1 = Counter(words)
print(cnt1) # Counter({'Lee': 3, 'yun': 2, 'bang': 1})

words = "yuneene shop"
cnt2 = Counter(words)
print(cnt2) # Counter({'e': 3, 'n': 2, 'y': 1, 'u': 1, ' ': 1, 's': 1, 'h': 1, 'o': 1, 'p': 1})

#Counter 주요 추가 매서드
#.most_common(n) : n개의 요소를 index 순으로 가져온다.
print(cnt2.most_common(4)) # [('e', 3), ('n', 2), ('y', 1), ('u', 1)]
#.elements() 개수만큼 반복되는 요소에 대한 이터레이터 반환
print(sorted(cnt2.elements())) # [' ', 'e', 'e', 'e', 'h', 'n', 'n', 'o', 'p', 's', 'u', 'y']
#.total() 총 개수 반환
print(cnt2.total()) # 12

 

▶ Counter() 객체 연습 백준 문제 풀이

https://www.acmicpc.net/problem/10815

"""
입력
첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 
둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 
숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다.
두 숫자 카드에 같은 수가 적혀있는 경우는 없다.
셋째 줄에는 M(1 ≤ M ≤ 500,000)이 주어진다.
넷째 줄에는 상근이가 가지고 있는 숫자 카드인지 아닌지를 구해야 할 M개의 정수가 주어지며, 이 수는 공백으로 구분되어져 있다.
이 수도 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다

출력
첫째 줄에 입력으로 주어진 M개의 수에 대해서, 
각 수가 적힌 숫자 카드를 상근이가 가지고 있으면 1을, 아니면 0을 공백으로 구분해 출력한다.
"""
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
"""

 

https://www.acmicpc.net/problem/10816

"""
입력
첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다.
둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다.
숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다.
셋째 줄에는 M(1 ≤ M ≤ 500,000)이 주어진다.
넷째 줄에는 상근이가 몇 개 가지고 있는 숫자 카드인지 구해야 할 M개의 정수가 주어지며,
이 수는 공백으로 구분되어져 있다.
이 수도 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다.

출력
첫째 줄에 입력으로 주어진 M개의 수에 대해서, 각 수가 적힌 숫자 카드를 상근이가 몇 개 가지고 있는지를 공백으로 구분해 출력한다.
"""
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})
#print(cnt)
rtn = ""
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
"""

 

☞ 파이썬 자습서 참고 사이트

 

collections — Container datatypes

Source code: Lib/collections/__init__.py This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.,,...

docs.python.org