백준 10816. 숫자 카드 - itemgetter, Counter

고봉진·2023년 3월 16일
0

TIL/코딩테스트

목록 보기
17/27

문제 링크

내 코드 :

from collections import Counter
n, *ls = list(map(int, open(0).read().split()))
counter = Counter(ls[:n])
for i in ls[n+1:]:
    print(counter.get(i, 0))

메모리 약 152MB, 시간 784ms

collections 모듈의 Counter를 사용했고, get 메서드를 사용해 counteri가 없는 경우에 대해 0을 반환하도록 처리했다.

itemgetter

hckex 님의 코드 :

import sys
from collections import Counter
from operator import itemgetter

N = int(sys.stdin.readline().rstrip())

numcard = sys.stdin.readline().rstrip().split()

counter = Counter(numcard)

M = int(sys.stdin.readline().rstrip())

candidate = sys.stdin.readline().rstrip().split()

result = str(itemgetter(*candidate)(counter))
result = result.replace(',', '')
        
print(result[1:-1])

메모리 약 131MB, 시간 492ms

Return a callable object that fetches item from its operand using the operand’s __getitem__() method. If multiple items are specified, returns a tuple of lookup values. 출처: 공식문서(v. 3.11.2)

파이썬 공식문서 정렬 HOW TO 에서 Operator 섹션에 itemgetter가 등장한다.

위에서 보여준 키 함수 패턴은 매우 일반적이므로, 파이썬은 액세스 함수를 더 쉽고 빠르게 만드는 편리 함수를 제공합니다. operator 모듈에는 itemgetter(), attrgetter()methodcaller() 함수가 있습니다.

from operator import itemgetter

students = [
    ("jane", 22, 'A'),
    ("dave", 32, 'B'),
    ("sally", 17, 'B'),
]

# tuple의 인덱스 1인 값으로 정렬된다.
result = sorted(students, key=itemgetter(1))
print(result)

hckex님의 코드에서는 counter에서 가져오고자 하는 값을 가져오기 위해 사용했다. 아래에서 보는 것 처럼 Counter 객체는 없는 값에 대해 0을 반환하는 것 같다.

Counter

eekdland 님의 코드 :

from collections import*
_,a,_,b=open(0)
c=Counter(a.split())
for v in b.split():print(c[v])

메모리 약 131MB, 시간 712ms

Counter 객체에는 get 메서드를 사용하지 않고도 없는 값에 대해 0이 출력되는 것 같다.

profile
이토록 멋진 휴식!

0개의 댓글