Algorithm/Problems

[프로그래머스] 위장 파이썬

공부좀하시졍 2022. 11. 2. 17:05

https://school.programmers.co.kr/learn/courses/30/lessons/42578

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

from itertools import combinations
 
def solution(clothes):
    cb = []
    tmp = []
    for i in range(len(clothes)):
        tmp.append(clothes[i][1])
    
    for i in range(len(set(tmp))):
        cb.append(list(combinations(tmp,i)))
    
    
    if len(set(tmp)) == 1:
        return len(clothes)
    else:
        return len(clothes) + len(cb)

내가 작성한 코드 😥

주어진 테스트코드를 생각했을 때 len(clothes)와 조합을 이용해서 answer를 구할 수 있을 것 같았는데 print문을 사용하며 확인해봤을 때, 맘처럼 되지 않았다..

 

def solution(clothes):
    items = {}
    answer = 1
    
    for item, category in clothes:
        # items에 category가 없다면 0 있으면 기존 값 + 1
        items[category] = items.get(category, 0) + 1
    
    for category in items:
        answer *= (items[category] + 1)
    
    return answer - 1

다른 풀이🙄

 

결과적으로 내가 생각했던 방식부터 잘못됐다!

 

(종류 수 + 1) * (종류 수 + 1) -1 방식으로 구해야한다. 이때 -1은 아무것도 입지 않았을 경우를 제거해 주는 것이다.

딕셔너리를 이용해서 category를 key, 각 종류의 개수를 value로 설정한 count table을 만든 다음에 위에서 언급한 식을 두번째 for문으로 계산해준다.

 

 

counter, reduce를 이용하는 풀이법도 있는데 reduce 식이 이해되지 않는다,,,