나의 풀이
from collections import Counter
# 종류가 매핑 -> 딕셔너리 사용
def solution(clothes):
answer = 1
cloth_map = {}
for i in range(len(clothes)): # O(N)
cloth_map[clothes[i][0]] = clothes[i][1]
category_count = Counter(cloth_map.values()) # O(종류 개수)
# Counter는 iterable한 객체를 받아서 각 요소의 개수를 세어서 dict로 만들어준다
for i in category_count.values():
answer = answer * (i + 1)
return answer - 1
Counter를 쓰지 않고 개수를 바로 딕셔너리로 받은 풀이
def solution(clothes):
answer = 1
cloth_map = {}
# 옷의 종류별 개수를 수동으로 세기
for cloth in clothes:
cloth_type = cloth[1]
if cloth_type in cloth_map:
cloth_map[cloth_type] += 1
else:
cloth_map[cloth_type] = 1
# 각 종류별로 개수를 곱하여 모든 조합 구하기
for count in cloth_map.values():
answer *= (count + 1)
return answer - 1
생각 과정
의상의 총 개수는 각 의상의 개수+1를 누적 곱(ex 의상이 2개면 3가지 경우가 존재) - 1(아무것도 안 고른 경우 제외) 로 구해진다. 그럼 주어진 clothes 리스트에서 종류 마다의 개수를 알아내야하는데, 종류와 값이 매핑되있으므로 딕셔너리를 생각했다. 주의할 점은 딕셔너리로 바꿀 때 종류를 key로 둘 수 없다는 것이다. key는 같은 값을 가질 수 없기 때문에 종류를 value로 하고 의상이름을 key로 하여 딕셔너리를 만들었다. 마지막으로 같은 종류 마다의 개수를 셀 때 Counter를 이용했다.
정리
1. 값과 값이 매핑되있는 형태라면 key-value 구조인 딕셔너리를 생각할 수 있다
2. Counter는 iterable한 객체를 받아서 각 요소의 개수를 세어서 dict로 만들어준다'Algorithm > 문제 풀이' 카테고리의 다른 글
| 프로그래머스 Lv2. 카펫 - Python (1) | 2024.02.07 |
|---|---|
| 프로그래머스 Lv2. 소수찾기 - Python (7) | 2024.02.06 |