jeeyeonLIM / coding_test

Let's practice the coding test!
1 stars 0 forks source link

Level2. 위장 #52

Open jeeyeonLIM opened 3 years ago

jeeyeonLIM commented 3 years ago

문제 설명

종류 이름
얼굴 동그란 안경, 검정 선글라스
상의 파란색 티셔츠
하의 청바지
겉옷 긴 코트

스파이가 가진 의상들이 담긴 2차원 배열 clothes가 주어질 때 서로 다른 옷의 조합의 수를 return 하도록 solution 함수를 작성해주세요.

제한사항

clothes의 각 행은 [의상의 이름, 의상의 종류]로 이루어져 있습니다. 스파이가 가진 의상의 수는 1개 이상 30개 이하입니다. 같은 이름을 가진 의상은 존재하지 않습니다. clothes의 모든 원소는 문자열로 이루어져 있습니다. 모든 문자열의 길이는 1 이상 20 이하인 자연수이고 알파벳 소문자 또는 '_' 로만 이루어져 있습니다. 스파이는 하루에 최소 한 개의 의상은 입습니다.

입출력 예

clothes return
[[yellow_hat, headgear], [blue_sunglasses, eyewear], [green_turban, headgear]] 5
[[crow_mask, face], [blue_sunglasses, face], [smoky_makeup, face]] 3

입출력 예 설명

예제 #1

예제 #2

jeeyeonLIM commented 3 years ago

나의 코드

Ver1. 실패한 코드 ❌

from collections import Counter
def solution(clothes):
    clothes_type = [j for i, j in clothes] # 의상의 종류만 추출해서 담기.
    hash_map = Counter(clothes_type)        # dict 활용해 갯수 세기.
    #print(hash_map)
    hash_map_len = len(list( hash_map.values()) )

    if hash_map_len != 1: # 의상 종류가 한개 이상인 경우
        answer_2=1
        for i in hash_map.values(): 
             answer_2 *= i
        return answer_2
    return len(clothes_type) 

Ver2. 최종 버전

jeeyeonLIM commented 3 years ago

모범답안

Ver1. from collections import Counter 활용하지 않기.

def solution(clothes):
    answer = {}
    for i in clothes:
        if i[1] in answer: answer[i[1]] += 1
        else: answer[i[1]] = 1
    cnt = 1
    for i in answer.values():
        cnt *= (i+1)
    return cnt - 1

Ver2. 최대한 간결하게. reduce 활용

def solution(clothes):
    from collections import Counter
    from functools import reduce
    cnt = Counter([kind for name, kind in clothes])
    answer = reduce(lambda x, y: x*(y+1), cnt.values(), 1) - 1
    return answer
jeeyeonLIM commented 3 years ago

다시 풀기

from functools import reduce   # 파이썬 3에

def solution(clothes):

    # 해시맵 생성 
    hash_map = {}
    for i in clothes:
        if i[1] not in hash_map:
            hash_map[i[1]] = 1 # 굳이 yellowhat이렇게 담아줄필요가 없음. 개수만 
        else :
            hash_map[i[1]] += 1
    #print(hash_map)

    # 해시맵은 from collections import Counter 에서 Counter 함수를 이용할 수도 있음.
    hash_map = Counter([y for x,y in clothes])
    print(hash_map) # Counter({'headgear': 2, 'eyewear': 1})

    return reduce(lambda x,y:(x+1)*(y+1)-1, hash_map.values()) 

    # -1 은 (0,0)인 경우 제외해야 하므로!!