
💡문제접근
- 딕셔너리를 이용해서 접근하면 된다고 생각하고 바로 코드를 작성했는데 계속 시간초과가 나와서 어떻게 하면 줄일 수 있나 하고 구글링을 해보니
defaultdict
를 사용해야한다고 질문게시판에 나와있었다.
- 입력값이 없을 때까지 입력을 하는 문제로 아래 조건문처럼 공백이 들어갈 경우
break
를 실행하는 방법도 있지만 try ... except
예외 처리 구문을 통해서 EOFerror
를 처리해도 상관은 없다.
💡코드(메모리 : 34088KB, 시간 : 480ms)
from collections import defaultdict
import sys
input = sys.stdin.readline
total = 0
dict = defaultdict(int)
while True:
tree = input().rstrip()
if tree == "":
break
dict[tree] += 1
total += 1
li = list(dict.keys())
li.sort()
for i in li:
print("%s %.4f" % (i, dict[i] * 100 / total))
💡시간초과 코드
import sys
input = sys.stdin.readline
total = 0
dict = {}
while True:
tree = input().rstrip()
if tree == '\n':
break
if tree not in dict:
dict[tree] = 1
else:
dict[tree] += 1
total += 1
li = sorted(dict.keys())
for i in li:
print("%s %.4f" % (i, dict[i] * 100 / total))
📌 ★ [defaultdict] ★
- Python의 내장 모듈인
collections
의 defaultdict
클래스
defaultdict
클래스의 생성자로 기본값을 생성해주는 함수를 넘기면 모든 키에 대해서 값이 없는 경우 자동으로 생성자의 인자로 넘어온 함수를 호출하여 그 결과값으로 설정해준다.
>>> dict = defaultdict(int)
defaultdict
의 인수로 int를 전달하여 딕셔너리 dict를 생성한다. int를 기준으로 생성한 딕셔너리 d의 값은 항상 0
으로 초기화된다. 따라서 초기화를 위한 별도의 코드가 필요하지 않다.
💡소요시간 : 27m