프로그래머스 성격 유형 검사하기 문제를 풀었다.
딕셔너리에 성격 유형들을 저장해두고 점수를 더하려고 했는데 모든 유형들을 미리 정의하는 건 노가다라고 생각했다.
외부 함수인 defaultdict를 이용하여 기본 타입을 int로 셋팅
새로운 key가 추가될 때 기본 value는 0이 된다.
defaultdict를 쓰기 위해서는 collections 모듈 import 해야 한다.
defaultdict를 만들 때는 뒤에 value에 어떤 타입으로 기본값을 설정할지 명시
ex) int, str, list
기본값
int = 0
str = ""
list = []
from collections import defaultdict
dict = defaultdict(int)
먼저 선택지에 따라 점수가 다르므로 score라는 리스트를 만들어서 점수를 저장
default가 0인 딕셔너리를 만들어서 각 유형이 몇 점인지 저장
마지막에 하나씩 비교
from collections import defaultdict
def solution(survey, choices):
answer = ''
dict = defaultdict(int)
score = [0, 3, 2, 1, 0, 1, 2, 3]
for i, type in enumerate(survey):
if choices[i] <= 3:
dict[type[0]] += score[choices[i]]
elif choices[i] == 4:
continue
else: # 5,6,7
dict[type[1]] += score[choices[i]]
# 비교
if dict['R'] >= dict['T']:
answer += 'R'
else:
answer += 'T'
if dict['C'] >= dict['F']:
answer += 'C'
else:
answer += 'F'
if dict['J'] >= dict['M']:
answer += 'J'
else:
answer += 'M'
if dict['A'] >= dict['N']:
answer += 'A'
else:
answer += 'N'
return answer