Coding/프로그래머스

[해시] 위장 (★)

sinabro_dy 2022. 7. 21. 15:59
문제

 

내가 작성한 코드 (틀림)
from collections import deque

def solution(clothes):
    cloth_l = [i[1] for i in clothes]
    cloth = deque(set(cloth_l))
    cnt = 0
    
    while True:
        a = cloth.popleft()
        a_cnt = len([i[0] for i in clothes if i[1] == a])
        if not cloth:
            return len(cloth_l) + cnt
        else:
            v = 1
            for i in cloth:
                cloth_v = len([c[0] for c in clothes if c[1] == i] )
                v *= (cloth_v * a_cnt)
                cnt += v

> 코드 실행은 통과했지만, 제출 후 채점하기에서는 8문제만 맞춰서 28.6 / 100.0 점의 결과가 나왔습니다...

> 맞게 한거 같은데... ㅜㅜ

 

참고한 블로그
def solution(clothes):
    closet = {}
    answer = 1
    
    # 같은 종류의 옷끼리 묶어서 사전에 저장
    for cloth in clothes:
        if cloth[1] in closet.keys():
            closet[cloth[1]].append(cloth[0])
        else:
            closet[cloth[1]] = [cloth[0]]
    
    # 경우의 수 구하기            
    for value in closet.values():
        answer *= len(value) + 1
    
    # 아무것도 입지 않은 경우 하나 제외
    return answer-1

> 참고한 블로그

https://latte-is-horse.tistory.com/140

 

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

문제 설명 스파이들은 매일 다른 옷을 조합하여 입어 자신을 위장합니다. 예를 들어 스파이가 가진 옷이 아래와 같고 오늘 스파이가 동그란 안경, 긴 코트, 파란색 티셔츠를 입었다면 다음날은

latte-is-horse.tistory.com

> 종류별 옷의 수에서 +1을 하는 의미는 옷을 입지 않은 경우를 포함하는 것!! 왜 이 생각을 못했지... ㅜㅜ

 

from collections import Counter
from functools import reduce

def solution(clothes):
    # 1. 의상 종류별 Counter를 만든다.
    counter = Counter([type for clothe, type in clothes])

    # 2. 모든 종류의 count + 1을 누적하여 곱해준다
    answer = reduce(lambda acc, cur: acc*(cur+1), counter.values(), 1) - 1
    return answer

print(solution([["yellowhat", "headgear"], ["bluesunglasses", "eyewear"], ["green_turban", "headgear"]]))
출처: https://coding-grandpa.tistory.com/88 [개발자로 취직하기:티스토리]

> https://coding-grandpa.tistory.com/88

 

[프로그래머스] 위장 (해시 Lv. 2) - 파이썬 Python

0. 동일 유형 문제 [프로그래머스] 완주하지 못한 선수 (해시 Lv. 1) [프로그래머스] 전화번호 목록 (해시 Lv. 2) [프로그래머스] 위장 (해시 Lv. 2) [프로그래머스] 베스트 앨범 (해시 Lv. 3)   1. 문제

coding-grandpa.tistory.com

> 업그레이드 버전....

> reduce 함수는 여러 개의 데이터를 대상으로 누적 집계를 내기 위해 사용하는 함수이다. 굉장히 어렵다..

> 참고 블로그 (https://www.daleseo.com/python-functools-reduce/)