DevYoon

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์‹œ์†Œ์ง๊ฟ (Python) ๋ณธ๋ฌธ

PS/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์‹œ์†Œ์ง๊ฟ (Python)

gimewn 2023. 1. 31. 18:26

link ๐Ÿ”— https://school.programmers.co.kr/learn/courses/30/lessons/152996

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๐Ÿ”ฅ 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']