Algorithm/solution

프로그래머스 - 의상.py

dxwny 2024. 6. 6. 20:38

 

< 딕셔너리 기능을 더 활용한 풀이 >

def solution(clothes):
    closet = {}
    total = 1
    for cloth, typ in clothes:
        closet[typ] = closet.get(typ,0) + 1
    for typ in closet:
        total *= closet.get(typ)+1
        
    return total-1

 

 

< 기존 풀이 >

def solution(clothes):
    mapi = {}
    
    for cloth in clothes:
        if cloth[1] not in mapi.keys():
            mapi[cloth[1]] = 1
        else:
            mapi[cloth[1]] = mapi[cloth[1]]+1
    total = 1
    for j in mapi.values():
        total = total * (j+1)
    return total - 1

 

새로 알게 된 딕셔너리 문법

- 파이썬 딕셔너리 값 읽어오는 두 가지 방법

1. 인덱스 활용

dictionary[key] = value

-> 해당 key가 없을 때 key error가 발생한다.

 

2. .get() 활용

dictionary.get(key) = value / dictionary.get(key, 해당하는 key가 없는 경우 반환 값 지정) = value

-> 해당 key가 없을 때 none 값을 반환한다. 두 번째 인자에 원하는 반환 값을 지정해주면 해당 값을 반환해준다.

 

- 파이썬 딕셔너리는 for i in dictionary 에서 value가 아닌 key 값을 준다.