본문 바로가기
  • 시 쓰는 개발자
알고리즘/코테 스터디 (2022)

11/02 스터디

by poetDeveloper 2022. 11. 7.

10816 숫자카드2

핵심 Counter

import sys
from collections import Counter # 해당 원소들이 몇번 등장했는지 카운팅해서 dict로 반환

n = int(input()) # 숫자카드 n개
cardlist = list(map(int, sys.stdin.readline().strip().split()))
m = int(input()) # 정수 m개
numlist = list(map(int, sys.stdin.readline().strip().split()))

count = Counter(cardlist)

for i in range(m):
    if numlist[i] in count:
        print(count[numlist[i]], end = ' ')
    else:
        print(0, end=' ')

참고로, collections의 Counter함수는 다음과 같이 사용된다.

 

Counter는 "리스트"를 값으로 주게 되면 각 원소들이 몇 번 등장했는지 세어 딕셔너리 형태로 반환한다.
ex. 

number_list = [1,1,1,2,2,2,3,4,4,5,5,5,5,5,4,4,3,2,8,9]
abc = Counter(number_list)
print(abc)

 

출력값


1764 듣보잡

<방법1> 처음부터 단어들을 리스트가 아닌 집합으로 받고, a & b를 사용해서 간단하게 추출

▶ 교집합을 구할 때, 말 그대로 "집합"을 이용해서 intersection을 구해주는 게 하나의 포인트.

<방법2> 딕셔너리에 단어들을 하나씩 넣고, 해당 단어의 value에 1을 더해줌. 만약 똑같은 단어가 한번 더 들어가면 해당 값만 2가 될테니, value가 2인 key값들만 프린트해줌.

 

<방법3> Counter를 이용해서 듣지못한 애들을 넣고, 이 안에 보지도못한 애들이 있는지 체크.

import sys
from collections import Counter

n,m = map(int, sys.stdin.readline().strip().split())
nohear = [0] * n
nosee = [0] * m
#듣도못한
for i in range(n):
    nohear[i] = sys.stdin.readline().strip()
    
#보도못한
for i in range(m):
    nosee[i] = sys.stdin.readline().strip()

counter = Counter(nohear)
cnt = 0
chklist = []
for i in range(m):
    if nosee[i] in counter:
        cnt += 1
        chklist.append(nosee[i])

print(cnt)
chklist.sort()
for i in range(len(chklist)):
    print(chklist[i])

'알고리즘 > 코테 스터디 (2022)' 카테고리의 다른 글

11/20 스터디  (0) 2022.11.21
11/16 스터디  (0) 2022.11.16
11/14 스터디  (0) 2022.11.14
11/09 스터디  (0) 2022.11.09
11/07 스터디  (0) 2022.11.07