하루에 하나씩 공부하기
의상-LV2 본문
- 문제
코니가 가진 의상들이 담긴 2차원 배열 clothes가 주어질 때 서로 다른 옷의 조합의 수를 return 하도록 solution 함수를 작성해주세요.
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
- 키포인트
해시(딕셔너리) 생성도 못함
딕셔너리에서 value값만 어떻게 가져오지? -> for _, value in ~.items()
마지막 딕셔너리에서 key별 개수를 어떻게 합치고 곱해야할까?
- 코드
def solution(clothes):
hash_map={}
for name, kind in clothes:
# 해시맵이라는 딕셔너리에 key, value 저장
if kind in hash_map.keys():
hash_map[kind]+=[name]
else :
hash_map[kind]=[name]
# ex) hash_map : [['yellow_hat', 'headgear'], ['blue_sunglasses', 'eyewear'], ['green_turban', 'headgear']]
answer=1
for _, value in hash_map.items():
answer*=(len(value)+1)
# hash_map.items()는 튜플 형태로 반환
# ex) [('headgear', ['yellow_hat', 'green_turban']), ('eyewear', ['blue_sunglasses'])]
# len(value)는 kind별 리스트의 길이, 곧 옷 종류의 개수 출력
return answer-1
def solution(clothes):
hash_map = {}
for name, kind in clothes:
# 종류별로 개수 세기
hash_map[kind] = hash_map.get(kind, 0) + 1
answer = 1
for kind in hash_map:
answer *= (hash_map[kind] + 1)
return answer - 1
'파이썬' 카테고리의 다른 글
K번째수-LV1 (0) | 2025.03.09 |
---|---|
베스트앨범-LV3 (1) | 2025.03.09 |
전화번호 목록-LV2 (0) | 2025.02.27 |
완주하지 못한 선수-LV1 (0) | 2025.02.25 |
폰켓몬-LV1 (0) | 2025.02.25 |