[python ๊ธฐ์ดˆ] Code-kata week 2-4

EMMAยท2022๋…„ 3์›” 24์ผ
1

[wecode] Code-kata

๋ชฉ๋ก ๋ณด๊ธฐ
9/12

๐Ÿ–ฅ 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 ์ ์šฉ
  • dictionaryํ˜•ํƒœ๋กœ ๋งŒ๋“ค์–ด์„œ ์˜ค๋ฆ„์ฐจ์ˆœ ํ›„, 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 ๋‘ ๋ฒˆ์งธ ์ ‘๊ทผ ๋ฐฉ์‹

  • ์ฃผ์–ด์ง„ list ์ธ์ž์˜ ์š”์†Œ๋“ค์„ ์ฐจ๋ก€๋Œ€๋กœ ์ œ๊ฑฐ, ์ตœํ›„ ๋‚จ์€ k๊ฐœ์˜ ์ˆซ์ž๋ฅผ ๋ฐ˜ํ™˜
  • ์ด์ค‘ for๋ฌธ์œผ๋กœ ๊ฐ ์ˆซ์ž๋ฅผ ์ œ๊ฑฐ
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:"ํ”„๋ž‘์Šค"}
profile
์˜ˆ๋น„ ๊ฐœ๋ฐœ์ž์˜ ๊ธฐ์ˆ  ๋ธ”๋กœ๊ทธ | explore, explore and explore

0๊ฐœ์˜ ๋Œ“๊ธ€