Algorithm/1일 1코테

[🤷‍♀️ 프로그래머스 Python] 위장

대인보우 2020. 10. 23. 22:23
반응형

 


프로그래머스 연습문제 2단계

<위장>

- 해시 & python3 

 


문제 및 문제설명

programmers.co.kr/learn/courses/30/lessons/42578

 

코딩테스트 연습 - 위장

 

programmers.co.kr

 


내가 시도한 답

해시로 풀어야되는 문제라서 해시테이블을 만들어서 진행했다.

 

#1차 시도

# 1차 시도

def solution(clothes):
    hash_table = {}
    answer = 0
    
    for (v , k) in clothes:
        if k in hash_table:
            hash_table[k] += 1
            answer += 1
        else:
            hash_table[k] = 1
            answer += 1
    num = 1
    if len(hash_table.values()) == 1:
        return answer
    else:
        for i in hash_table.values():
            num = num * i
    
    return answer+num

#2차 시도

# 2차 시도 - 통과
def solution(clothes):
    hash_table = {} #저장할 hash_table 생성
    
    for (v , k) in clothes: # clothes에서 쌍을 꺼내
        if k in hash_table: # 카테고리를 key로 삼아 저장
            hash_table[k] += 1
        else:
            hash_table[k] = 1
    # 위의 식을 수행하고 나면 각 카테고리별 옷의 갯수가 저장된다
    # 경우의 수를 활용한다
    answer = 1
    for i in hash_table.values():
    	# 각 카테고리의 옷의 갯수를 answer에 곱하되 해당 카테고리를 착용하지 않는다는 조건이 
        # 필요하기 때문에 1을 더해준다.
        answer *= (i + 1)
    
    return answer-1 # 아무 옷도 안입는다는 조건을 넣기 위해 1을 뺀다

 


다른사람 풀이 #1

import collections
from functools import reduce

def solution(c):
    return reduce(lambda x,y:x*y,[a+1 for a in collections.Counter([x[1] for x in c]).values()])-1

다른사람 풀이 #2

def solution(clothes):
    clothes_type = {}

    for c, t in clothes:
        if t not in clothes_type:
            clothes_type[t] = 2
        else:
            clothes_type[t] += 1

    cnt = 1
    for num in clothes_type.values():
        cnt *= num

    return cnt - 1

 

수학 공부 제대로 안한게 이렇게 뒤통수 칠 줄은 몰랐다😭

 


reduce 함수?

reduce(함수, 순서형 자료)

from functools import reduce 
reduce(lambda x, y: x + y, [0, 1, 2, 3, 4])
# 10
반응형