Notice
Recent Posts
Recent Comments
Link
์ผ | ์ | ํ | ์ | ๋ชฉ | ๊ธ | ํ |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
Tags
- ํ ์ดํ๋ก์ ํธ
- ์ฝ๋ฉ
- JS
- ๊ฐ๋ฐ
- heapq
- ํฌ๋กค๋ง
- ๋๋ฆผ์ฝ๋ฉ
- ์๊ณ ๋ฆฌ์ฆ
- ๊ทธ๋ฆฌ๋
- ์ฝ๋ฉํ ์คํธ
- mongodb
- node.js
- ํ๋ก ํธ์๋
- CSS
- ์ฝ๋ฉ์ ํ
- ํ๋ก๊ทธ๋๋จธ์ค
- Python
- javascript
- error
- Til
- ๋ชจ๊ฐ์ฝ
- KDT
- ๋ฐฑ์ค
- ํ์ด์ฌ
- fe
- HTML
- ํ๋ก์ ํธ
- react
- ๋ ธ๋ง๋์ฝ๋
- ๊ตญ๋น์ง์
Archives
- Today
- Total
๐ฑ → ๐ณ
[ํ๋ก๊ทธ๋๋จธ์ค] ๊ทค ๊ณ ๋ฅด๊ธฐ - Python ๋ณธ๋ฌธ
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/138476
์ค๊ณ ๋ฐฉ๋ฒ
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
'Algorithms' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค] ์ ํ๋ฒํธ ๋ชฉ๋ก - python (0) | 2023.08.29 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค] ์์ ์ฐพ๊ธฐ - python (0) | 2023.08.25 |
[ํ๋ก๊ทธ๋๋จธ์ค] ๋ฉ๋ฆฌ๋ฐ๊ธฐ - Python (0) | 2023.08.14 |
[ํ๋ก๊ทธ๋๋จธ์ค] N๊ฐ์ ์ต์๊ณต๋ฐฐ์ - Python (0) | 2023.08.13 |
[ํ๋ก๊ทธ๋๋จธ์ค] ์ฒด์ก๋ณต - python (0) | 2023.08.02 |