알고리즘 문제풀이
프로그래머스 위장 파이썬
dolchimdae
2022. 4. 8. 18:03
반응형
https://programmers.co.kr/learn/courses/30/lessons/42578
1 케이스에 대해 시간초과 뜬 내 코드 😇.. :
from itertools import combinations
#clothes = [["yellowhat", "headgear"], ["bluesunglasses", "eyewear"], ["green_turban", "headgear"]]
def solution(clothes):
d = {}
for c in clothes:
if c[1] in d:
d[c[1]] += 1
else:
d[c[1]] = 1
# clothes 의 value(의상종류)별로 count한 list
data = list(d.values())
n = len(data)
result = 0
# 각 index 별 combination 별로 의상 수를 곱해 경우를 구한다
for i in range(1,n+1):
com = list(combinations([x for x in range(n)],i))
print(com)
for c in com:
gop = 1
for x in c:
gop *= data[x]
result += gop
return result
너무 복잡하게 썼었다.. 각 경우를 조합으로 나눌 게 아니라 의상을 선택 할 때
선택하지 않는 경우까지 포함해 구하면 간단했다.
어떤 의상도 선택하지 않는 경우를 고려해 1 뺀다.
def solution(clothes):
answer = 1
##
types = [type for name,type in clothes]
counts = [types.count(type) for type in set(types)]
# 의상종류 별 의상들 + 아예 안고를 때 1
for c in counts:
answer *= c + 1
# 의상 모두 고르지 않은 경우
answer -= 1
return answer
반응형