파이썬 알고리즘/BOJ

[Algorithm] 백준 #10816 숫자 카드 2

walbe0528 2024. 6. 18. 10:37
728x90
반응형

 

내 풀이

SOLVE1) 파이썬 defaultdict 이용

 

import sys
from collections import defaultdict
input = sys.stdin.readline

N = int(input())
nums = list(map(int, input().split()))
dict = defaultdict(int)
for i in nums:
    dict[i] += 1

M = int(input())
targets = list(map(int, input().split()))

for i in targets:
    print(dict[i], end=' ')

 

 

 

SOLVE2) Counter 모듈 사용

 

import sys
from collections import Counter
input = sys.stdin.readline

N = int(input())
nums = list(map(int, input().split()))
M = int(input())
targets = list(map(int, input().split()))

cnt = Counter(nums)
# print(cnt)
# Counter({10: 3, 3: 2, -10: 2, 6: 1, 2: 1, 7: 1})
for target in targets:
    print(cnt[target], end=' ')

 

 

Counter 모듈 사용

  • 여러 형태의 데이터를 인자로 받아서, 각 원소가 몇번씩 나오는지 저장된 객체를 얻는다.
  • 데이터의 갯수를 셀때 유용
  • 데이터의 갯수가 많은 순으로 졍렬된 배열을 리턴하는 most_common( )메서드 제공
    • 안에 숫자 K인자로 넣으면, 가장 갯수가 많은 K개의 데이터 얻을 수 있다
from collections import Counter
counter = Counter("hello world")
>>> counter
Counter({'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})


Counter('hello world').most_common()
[('l', 3), ('o', 2), ('h', 1), ('e', 1), (' ', 1), ('w', 1), ('r', 1), ('d', 1)]

 

728x90