문제 설명
https://school.programmers.co.kr/learn/courses/30/lessons/42578
1. 옷의 종류와 이름이 주어졌을 때, 각 종류별로 최대 1가지 의상만 선택할 수 있다.
2. 이때 서로 다른 옷의 조합의 수를 구하는 문제다.
풀이
딕셔너리에 종류에 따른 옷의 개수를 저장해주었다.
각 종류에서 하나를 선택하거나 아무것도 선택하지 않는 경우가 있으므로, 경우의 수를 (옷의 개수 + 1)로 설정했다.
answer에 모든 경우의 수를 곱해준 뒤, 마지막으로 아무것도 선택하지 않는 경우를 빼주었다.
코드
def solution(clothes):
answer = 1
dic = {}
for name,category in clothes:
if category not in dic:
dic[category] = 1
else:
dic[category] += 1
for key in dic:
answer *= (dic[key] + 1)
return answer - 1
다른 풀이
https://school.programmers.co.kr/learn/courses/30/lessons/42578/solution_groups?language=python3
from collections import Counter
from functools import reduce
def solution(clothes):
cnt = Counter([kind for name, kind in clothes])
answer = reduce(lambda x, y: x*(y+1), cnt.values(), 1) - 1
return answer
프로그래머스에서 다른 풀이를 보니 Counter 클래스와 reduce함수를 사용한 풀이가 있어서 정리해보았다.
Counter 클래스
중복된 데이터의 개수를 딕셔너리 형태로 반환해준다.
Counter(["hi", "hey", "hi", "hi", "hello", "hey"])
>>> Counter({'hi': 3, 'hey': 2, 'hello': 1})
reduce 함수
반복 가능한 객체(문자열, 리스트, 딕셔너리, 세트)내 이전 연산 결과와 각 요소를 연산해서 반환해주는 함수
reduce(집계 함수, 순회 가능한 데이터[, 초기값])
from functools import reduce
target = list(range(1, 21))
print(reduce(lambda x, y: x + y, target))
참고
https://www.daleseo.com/python-collections-counter/
https://www.daleseo.com/python-functools-reduce/
https://heytech.tistory.com/49
'코테 준비' 카테고리의 다른 글
[프로그래머스] 줄 서는 방법 (python) (2) | 2024.04.12 |
---|---|
[프로그래머스] 다리를 지나는 트럭 (python) (0) | 2024.04.07 |
[프로그래머스] 호텔 대실 (0) | 2024.04.04 |
[프로그래머스] 멀짱한 사각형 (0) | 2024.03.29 |
[프로그래머스] 2018 kakao blind recruitment [3차] 방금그곡 (python) (0) | 2024.03.28 |