[Programmers] 의상 (해시 Lv. 2) - Python

꼬마요리사레미·2023년 5월 25일

Algorithm

목록 보기
5/41

1. 문제


의상

2. 풀이


코드
def solution(clothes):
    clothes_dict = {}
    answer = 1
    for clothe in clothes:
        cloth_type = clothe[1]
        if cloth_type not in clothes_dict:
            clothes_dict[cloth_type] = 1
        else:
            clothes_dict[cloth_type] += 1
    for value in clothes_dict.values():
        answer *= (value + 1)
    return answer - 1
입력 및 출력
clothes = [["yellow_hat", "headgear"], ["blue_sunglasses", "eyewear"], ["green_turban", "headgear"]]

>> 6

3. 로직


  1. 빈 딕셔너리 'clothes_dict'을 초기화한다.

  2. 'clothe' 리스트의 두 번째 요소인 의상의 종류 'cloth_type'을확인한다.

  3. 만약 'cloth_type''clothes_dict' 딕셔너리에 존재하지 않는다면, 새로운 키로 현재 의상의 종류를 추가하고 값을 1로 설정한다.

  4. 만약 'cloth_type''clothes_dict' 딕셔너리에 이미 존재한다면, 해당 종류의 의상이 이미 추가된 것이므로 값을 1 증가시킨다.

  5. 'clothes_dict' 딕셔너리에는 각 의상의 종류별로 개수가 저장된다.

  6. 'clothes_dict' 딕셔너리의 값들을 확인하면서, 각 의상의 종류별로 선택 가능한 경우의 수를 계산한다.

  7. 'value'변수에 1을 더해서, 각 의상의 종류별로 선택하지 않은 경우를 포함시키고, 해당 값에 'answer' 변수에 누적곱으로 계산한다.

  1. 'answer' 변수에 1을 빼서, 아무 옷도 선택하지 않은 경우의 수를 제외한다.

4. 사용한 자료형


딕셔너리(Dictionary)

딕셔너리(Dictionary)는 키(key)와 값(value)의 쌍으로 이루어진 데이터를 저장하는 자료형이다. 딕셔너리는 중괄호 {}로 감싸고, 키와 값은 콜론 :으로 구분하여 표현한다.

1. 딕셔너리 초기화
clothes_dict = {}
2. 딕셔너리 값 할당
  • 의상의 종류별 의상의 이름을 할당
for cloth in clothes:
    cloth_type = cloth[1]
    cloth_item = cloth[0]
    if cloth_type not in clothes_dict:
        clothes_dict[cloth_type] = [cloth_item]
    else:
        clothes_dict[cloth_type].append(cloth_item)
{
    "headgear": ["yellow_hat", "green_turban"],
    "eyewear": ["blue_sunglasses"]
}
  • 의상의 종류별 개수를 할당
for cloth in clothes:
    cloth_type = cloth[1]
    if cloth_type not in clothes_dict:
        clothes_dict[cloth_type] = 1
    else:
        clothes_dict[cloth_type] += 1
{
    "headgear": 2,
    "eyewear": 1
}
3. 딕셔너리 키와 값 빼내기
# items(): (키, 값) 쌍을 나타내는 튜플로 구성된 객체를 반환
items = clothes_dict.items()
print(items)
# 출력: dict_items[('headgear', 2), ('eyewear', 1)])

# keys(): 키들로 구성된 객체를 반환
keys = clothes_dict.keys()
print(keys)
# 출력: dict_keys(['headgear', 'eyewear'])

# values(): 값들로 구성된 객체를 반환
values = clothes_dict.values()
print(values)
# 출력: dict_values([2, 1])

딕셔너리 뷰(View) 객체는 리스트 형태로 직접 반환되지는 않는다. 이 객체를 리스트로 변환하기 위해서는 반복(iteration)을 수행하거나list()함수를 사용하여 리스트로 변환해야 한다.

0개의 댓글