출처 https://programmers.co.kr/learn/courses/30/lessons/42578
clothes_dict 을 만들어서 옷의 종류를 key로 설정.
어차피 옷의 이름이 중요한게 아니므로 value에는 해당 종류의 옷의 개수로 설정.
def solution(clothes):
answer = 0
clothes_dict = {}
for name, kind in clothes:
if kind in clothes_dict:
tmp = clothes_dict.get(kind)
clothes_dict[kind] = clothes_dict.get(kind) + 1
else:
clothes_dict[kind] = 1
for val in clothes_dict.values():
answer += val
if (val != 1) and (len(clothes_dict) !=1):
answer += val
return answer
수식 일반화를 잘못시킴...
def solution(clothes):
answer = 1
clothes_dict = {}
for name, kind in clothes:
if kind in clothes_dict:
clothes_dict[kind] = clothes_dict.get(kind) + 1
else:
clothes_dict[kind] = 1
for val in clothes_dict.values():
answer *= (val+1)
return answer-1
ex)
x:a개 y:b개 z:c개 일 때
a + b + c + ab + bc + ac + abc
결과값은 (a+1)(b+1)(c+1)-1
각 (value값+1)을 모두 곱하고 -1 하는거라는 수식을 구함
collections의 Counter이용
from collections import Counter
from functools import reduce
def solution(clothes):
cnt = Counter([kind for name, kind in clothes])
answer = reduce(lambda x, y: x*(y+1), cnt.values(), 1) - 1
return answer
from collections import Counter
from functools import reduce
def solution(c):
return reduce(lambda x,y:x*y,[a+1 for a in Counter([x[1] for x in c]).values()])-1
Counter(iterable)
from collections import Counter
해시 가능한 객체를 세기 위한 dict 서브 클래스
요소가 dict key로 저장되고 개수가 dict value로 저장
clothes = [["yellowhat", "headgear"], ["bluesunglasses", "eyewear"], ["green_turban", "headgear"]]
Counter([kind for name, kind in clothes]))
lambda
lambda 매개변수 : 표현식
lambda 매개변수: 식1 if 조건식 else 식2
reduce(함수, 순서형 자료)
from functools import reduce
반복 가능한 객체의 각 요소를 지정된 함수로 처리한 뒤 이전 결과와 누적해서 반환하는 함수
reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]) #15