honey_pot

[python] 위장 (Counter, reduce 함수) 본문

문제 풀이

[python] 위장 (Counter, reduce 함수)

_tera_ 2021. 11. 4. 19:29

Counter

collections 모듈

리스트나 딕셔너리 안에 존재하는 원소의 개수를 세서 딕셔너리 자료형으로 반환한다. {'A':4}

 


reduce

functools 내장 모듈

데이터에 집계 함수를 반복해서 계산해줌

reduce(집계 함수, 순회 가능한 데이터[, 초기값])

 

첫번째 인자는 accumulator, 두번째 인자는 현재값(current value)


 

https://programmers.co.kr/learn/courses/30/lessons/42578?language=python3 

 

코딩테스트 연습 - 위장

 

programmers.co.kr

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

⭐ 1번째 데이터를 kind(종류)로, 0번째 데이터를 해당 kind의 name(이름)으로 정하고 Counter 하여 cnt에 저장한다.

1부터 cnt(kind의 개수)+1 을 곱해서 모든 경우의 수를 구하고 하나도 착용하지 않는 경우의 수인 1을 뺀다.

'문제 풀이' 카테고리의 다른 글

[python] 다리를 지나는 트럭 - queue  (0) 2021.11.06
[python] 프린터 - queue, any  (0) 2021.11.06
[python] 피보나치의 수  (0) 2021.09.14
[python] JadenCase 문자열 만들기  (0) 2021.09.13
[python] 행렬의 곱셈  (0) 2021.09.12
Comments