PS

[백준] 10816번 : 숫자 카드 2(counter)- 파이썬[Python]

choisanghyun 2022. 1. 13. 10:08
728x90

문제

 

10816번: 숫자 카드 2

첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,

www.acmicpc.net

풀이

import sys
from collections import Counter

M=int(sys.stdin.readline())
list1=list(map(int,sys.stdin.readline().split()))
N=int(sys.stdin.readline())
list2=list(map(int,sys.stdin.readline().split()))

c= Counter(list1)

for i in list2:
  if i in c:
    print(c[i], end=' ')
  else:
    print(0, end=' ')

위 문제는 list의 count함수를 사용하면 문제가 풀리긴 하지만 시간초과가 발생한다.

collections 패키지의 Counter 함수를 사용하면 시간초과 없이 문제를 해결할 수 있다.

 

클래스 2 문제를 풀면서 시간초과를 줄이기 위한 팁을 알게 되었다.

input() 대신 sy.stdin.readline() 사용하기

count() 대신 Counter() 사용하기 -> Counter은 빈도수를 딕셔너리 형태로 만듬