DevYoon
[ํ๋ก๊ทธ๋๋จธ์ค] ์์์ง๊ฟ (Python) ๋ณธ๋ฌธ
link ๐ https://school.programmers.co.kr/learn/courses/30/lessons/152996
๐ฅ dict์ weight์ ๊ฐ์๋ฅผ ๋ชจ๋ ๊ธฐ๋กํ๋ ๋ฐฉ์๊น์ง ๋ ์ฌ๋ ธ๋๋ฐ, ๊ทธ ํ๋ก ์ ํ๋ฆฌ์ง ์์์ ๋ค๋ฅธ ๋ถ์ ํ์ด๋ฅผ ์ฐธ๊ณ ํด์ ํ์๋ค.
๐ฅ ๋์ฌ ์ ์๋ ๊ฒฝ์ฐ์ ์๋ (1:1), (2:3), (2:4), (3:2), (3:4), (4:2), (4:3) ์ผ๋ก 7๊ฐ์ง์ด๋ค.
from collections import defaultdict
def solution(weights):
answer = 0
dict = defaultdict(int)
for wei in weights:
answer += dict[wei]+dict[wei*(2/3)]+dict[wei*(2/4)]+dict[wei*(3/2)]+dict[wei*(3/4)]+dict[wei*2]+dict[wei*(4/3)]
dict[wei] += 1
return answer
defaultdict
- ํ์ด์ฌ์ ๋ด์ฅ ๋ชจ๋์ธ collections์ ํด๋์ค
- ๋์ ๋๋ฆฌ์ ๊ธฐ๋ณธ๊ฐ ์ค์ ๊ฐ๋ฅ
from collections import defaultdict
# defaultdict(<class 'int'>, {})
dict_int = defaultdict(int)
# 0
dict_int['test']
# defaultdict(<class 'list'>, {})
dict_list = defaultdict(list)
# []
dict_list['test']
# defaultdict(<class 'set'>, {})
dict_set = defaultdict(set)
# set()
dict_set['test']