Development

[프로그래머스] 위장 본문

코딩테스트/Python

[프로그래머스] 위장

yo~og 2021. 7. 28. 17:27
반응형

ㅠㅠ 딕셔너리까지 만들었는데 계산을 어떻게 할건지 고민하다가.. 블로그봤다 ㅎ.. 블로그에서 계산 방법만 보고 코드는 내가 짜봤다!ㅠ 설명은 코드 안에 들어가있다.

 

내 코드

def solution(clothes):
    
    dic = {}
    sol=1
    
    #종류를 key, 수를 value로 딕셔너리를 만들어준다.
    for key in clothes:
        if key[1] in dic:
            dic[key[1]]+=1
        else:
            dic[key[1]] = 1

	# 각 종류별로 입는 경우의 수를 곱해준다. 마지막에 전부 입지 않는 경우의 수를 빼준다.
    for key in dic:
        sol*=dic[key]+1
    return sol-1

 

다른사람 코드

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

kind만 있는 list를 만들어서 Counter을 사용하여 각각의 개수를 센다. reduce를 사용하여 계산을 한다.

 

 

Counter


데이터의 개수를 셀 때 사용한다.

from collections import Counter

Counter('hello world')

# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})



Counter('hello world').most_common(1) # 상위요소 하나 출력
# [('l', 3)]
Counter('hello world').most_common(2) # 상위요소 두개 출력
# [('l', 3), ('o', 2)]

 

 

reduce


주로 데이터의 누적 집계를 내기 위해서 사용한다.

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

 

from functools import reduce

result = reduce(lambda x,y:x+y,[1,2,3,4,5]) 

print(result)

# 15 초기값이 0에서 시작




from functools import reduce

result = reduce(lambda x,y:x+y,[1,2,3,4,5],100)

print(result)

# 115 초기값이 100에서 시작
반응형
Comments