๐ŸŒฑ → ๐ŸŒณ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๊ทค ๊ณ ๋ฅด๊ธฐ - Python ๋ณธ๋ฌธ

Algorithms

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๊ทค ๊ณ ๋ฅด๊ธฐ - Python

BAY 2023. 8. 15. 08:41
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/138476

 

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

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

programmers.co.kr

 

์„ค๊ณ„ ๋ฐฉ๋ฒ•

python์˜ dict๋ฅผ ์‚ฌ์šฉ

def solution(k, tangerine):
    cnt = 0
    dic = {}
    for i in tangerine:
        if key์— ์—†์œผ๋ฉด : 
            dic key๋กœ ์ถ”๊ฐ€ 
        else:
            key์˜ value += 1
            
    dic์˜ value๊ฐ€ ํฐ ์ˆœ์œผ๋กœ sorting 
    for i in dic์˜ val:
        cnt += 1
        if val์˜ ํ•ฉ >= k: break
    return cnt

์ฝ”๋“œ

def solution(k, tangerine):
    cnt = 0
    dic = {}
    for i in tangerine:
        if i not in dic :
            dic[i] = 1
        else:
            dic[i] += 1
            
    sorted_val = sorted(list(dic.values()), reverse=True)
    val = 0
    
    for i in sorted_val:
        val += i
        cnt += 1
        if val >= k: break
    return cnt

 

๋‹ค๋ฅธ ์‚ฌ๋žŒ ํ’€์ด 

import collections
def solution(k, tangerine):
    answer = 0
    cnt = collections.Counter(tangerine)

    for v in sorted(cnt.values(), reverse = True):
        k -= v
        answer += 1
        if k <= 0:
            break
    return answer

 

Counter ํด๋ž˜์Šค๋Š” ๋”•์…”๋„ˆ๋ฆฌ์˜ ์„œ๋ธŒ ํด๋ž˜์Šค๋กœ, ๊ฐ ์š”์†Œ๋ฅผ ํ‚ค๋กœ ๊ฐ€์ง€๊ณ  ํ•ด๋‹น ์š”์†Œ์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ฐ’์œผ๋กœ ๊ฐ–๋Š” ๋”•์…”๋„ˆ๋ฆฌ์™€ ์œ ์‚ฌํ•œ ํ˜•ํƒœ๋ฅผ ๊ฐ€์ง Counter ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์š”์†Œ์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๊ฑฐ๋‚˜ ๋นˆ๋„ ๋ถ„์„์„ ์‰ฝ๊ฒŒ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ์Œ

 

Counter ๊ฐ„๋‹จํ•œ ์˜ˆ์‹œ 

from collections import Counter

# ๋ฆฌ์ŠคํŠธ์˜ ์š”์†Œ๋“ค์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๊ธฐ
my_list = [1, 2, 3, 1, 2, 2, 4, 5]
counter = Counter(my_list)
print(counter)  # ์ถœ๋ ฅ ๊ฒฐ๊ณผ: Counter({2: 3, 1: 2, 3: 1, 4: 1, 5: 1})

# ๋ฌธ์ž์—ด์˜ ๋ฌธ์ž ๋นˆ๋„๋ฅผ ์„ธ๊ธฐ
my_string = "hello"
counter = Counter(my_string)
print(counter)  # ์ถœ๋ ฅ ๊ฒฐ๊ณผ: Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

# Counter ๊ฐ์ฒด์˜ ๋ฉ”์†Œ๋“œ ์‚ฌ์šฉ
print(counter.most_common(2))  # ๊ฐ€์žฅ ๋นˆ๋„๊ฐ€ ๋†’์€ 2๊ฐœ ์š”์†Œ ์ถœ๋ ฅ
# ์ถœ๋ ฅ ๊ฒฐ๊ณผ: [('l', 2), ('h', 1)]
728x90