๐ฅ Code-kata week2-4
๋ฌธ์
nums๋ ์ซ์๋ก ์ด๋ฃจ์ด์ง ๋ฐฐ์ด์
๋๋ค.
๊ฐ์ฅ ์์ฃผ ๋ฑ์ฅํ ์ซ์๋ฅผ k ๊ฐ์๋งํผ return ํด์ฃผ์ธ์.
nums = [1,1,1,2,2,3], k = 2
return [1,2]
nums = [1], k = 1
return [1]
ํ์ด
1 ์ฒซ ๋ฒ์งธ ์ ๊ทผ ๋ฐฉ์
set(nums)
> count
์ ์ฉk
๋งํผ return ํ๋ค def top_k(nums, k):
std_list = list(set(nums))
my_dict = {}
cnt = 0
#{i:cnt}ํํ์ key-value ๊ฐ ์์ฑ
for i in std_list:
cnt = nums.count(i)
my_dict[i] = cnt
#my_dict์ value๋ฅผ ๊ธฐ์ค์ผ๋ก ์ ๋ ฌ ํ, ์ค๋ฆ์ฐจ์ -> tuple๋ก ์ถ๋ ฅ๋จ
sorted_dict = sorted(my_dict.items(), key = lambda item:item[1], reverse = True)
#range(k)๋งํผ value๊ฐ๋ค์ return
result = []
for i in range(k):
result.append(sorted_dict[i][0])
return result
2 ๋ ๋ฒ์งธ ์ ๊ทผ ๋ฐฉ์
def top_k(nums, k):
#์ด len(nums)๋ฒ inner for๋ฌธ์ ์คํํ๋ค
for i in range(len(nums)):
#set(nums) ๊ฐ์๊ฐ k๊ฐ๊ฐ ๋ ๊น์ง ์ซ์๋ฅผ ์ฐจ๋ก๋๋ก ์ ๊ฑฐ
for num in list(set(nums)):
if len(set(nums)) > k:
nums.remove(num)
else:
list(set(nums))
return list(set(nums))
additional notes)
lambda, sorted๋ฅผ ํ์ฉํ dictionary ์ ๋ ฌ
#tuple ์์๋๋ก ์ ๋ ฌ
sorted(my_dict.items(), key = lambda x:x[0])
#value๊ฐ ๊ธฐ์ค์ผ๋ก ์ ๋ ฌ
sorted(my_dict.items(), key = lambda x:x[1])
๊ทธ๋ฆฌ๊ณ ์ ๋ฌธ์ ๋ zip
์ ํ์ฉํด์ ํ ์๋ ์๋ค.
keys = [1,2,3]
values = ["ํ๊ตญ","๋ฏธ๊ตญ","ํ๋์ค"]
my_dict = dict(zip(keys,values))
>>> {1:"ํ๊ตญ", 2:"๋ฏธ๊ตญ", 3:"ํ๋์ค"}