티스토리 뷰

Computer/백준 풀이

[파이썬/백준10816] 숫자 카드 2

벼랑끝과학자 2022. 12. 18. 21:20

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

 

10816번: 숫자 카드 2

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

www.acmicpc.net

실버 4문제, 아주 쉬운편에 속하는 문제다.

이 문제도 전형적인 시간초과를 유도하는 문제같아서 내가 아는 한도에서 최대한 시간을 줄일 수 있도록 stdin의 readline을 사용해서 input 받았고, dictionary를 이용하는 코드를 작성해 보았다.

import sys

N = sys.stdin.readline().strip()

all_card_list = list(map(int, sys.stdin.readline().split()))
all_card_dict = {}

for num in all_card_list:
    if num not in all_card_dict.keys():
        all_card_dict[num] = 1
    else:
        all_card_dict[num] += 1

M = sys.stdin.readline().strip()

sg_card_list = list(map(int, sys.stdin.readline().split()))

for num in sg_card_list:
    if num not in all_card_dict.keys():
        print(0, end=' ')
    else:
        print(all_card_dict[num], end=' ')

로직은 아주 간단하다. 모든 카드를 입력받고 카드 숫자를 딕셔너리의 KEY로, 해당 카드의 장수를 Value로 저장한 dictionary를 생성했다.

그리고 상근이의 카드에 for문을 통해 하나씩 접근하여 위에서 만든 dictionary의 KEY값으로 전달하여 값이 없으면 0을 출력하고, value가 있으면 value를 출력하도록 했다.

결과는.. 맞기는 했지만, 뒤를 안닦은 것 같은 찝찝한 결과를 얻었다.

저 엄청난 메모리사용량... 굉장히 보기 거북(또는 토끼)하다.

메모리 사용량을 보는것이 매우 불편하다. 다행히 답은 맞췄지만...

그래서 메모리 사용량도 적고, 시간도 적게 걸린 다른 사람들의 파이썬 코드를 참고해보기로 했다.

 

어라 근데 큰 차이가 없다

찾아봤지만 생각보다 눈에띄는 좋은 결과를 가지고있는 답변이 없었다. 그래서 그냥 코드를 참고해보자는 느낌으로 짧은 코딩을 참고해보았다.

from sys import stdin
from collections import Counter 

n = int(stdin.readline())
counter = Counter(map(int, stdin.readline().split()))

m = int(stdin.readline())
list_m = map(int, stdin.readline().split())

for elem in list_m:
    print(counter[elem], end=" ")

https://www.daleseo.com/python-collections-counter/

그렇다, 고수들은 collections 모듈을 종종 사용하는것 같다. collections 모듈의 Counter는 중복된 데이터를 가지고있는 list를 인자로 넘기면 Counter([list]) >>> Counter({key:value}) 형태로 중복된 데이터의 갯수를 value로 하는 Dictionary를 갖는 Counter라는 객체를 반환한다.

이렇게 Counter객체를 이용하니 훨씬 깔끔하게 코드를 만들 수 있음을 참고할 수 있었다.

댓글