🏈sort 함수
🏈 defaultdict(data type)
collection 모듈의 클래스에요.
딕셔너리 형태를 이용하되 인자로 데이터
nums는 숫자로 이루어진 배열입니다.
가장 자주 등장한 숫자를 k 개수만큼 return해주세요.
<case 1>
nums = [1,1,1,2,2,3],
k = 2
return [1,2]
<case 2>
nums = [1]
k = 1
return [1]
저는 눈으로 일일히 확인해봐야하는 개린이인만큼 지저분하지만 0부터 100까지 다 찍는 수고를 했습니다.
이해는 됬어요.
근데 이해는 하되 금방 또 까먹을까 걱정이네요 ㅋㅋㅋ
from collections import defaultdict
def top_k(nums, k):
dict_ = defaultdict(int)
print('1', dict_)
check_list = []
print('2', check_list)
result = []
print('3',result)
for i in nums:
print(f'{i} 이렇게 커진다')
dict_[i] += 1
print(dict_[i],'-----------------------',dict_)
for j,k in dict_.items():
print('2번째 for문',j,k)
check_list.append([k,j])
print('check_list',check_list)
check_list.sort(reverse=True)
print('sort로 정렬',check_list)
for z in range(k):
result.append(check_list[z][1])
print(f'{check_list}입니다.',result)
return result
nums = [0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,999,999,999,1,30,30,30,]
print(top_k(nums,k=3))
❯ python test.py
1 defaultdict(<class 'int'>, {})
2 []
3 []
0.1 이렇게 커진다
1 ----------------------- defaultdict(<class 'int'>, {0.1: 1})
0.1 이렇게 커진다
2 ----------------------- defaultdict(<class 'int'>, {0.1: 2})
0.1 이렇게 커진다
3 ----------------------- defaultdict(<class 'int'>, {0.1: 3})
0.1 이렇게 커진다
4 ----------------------- defaultdict(<class 'int'>, {0.1: 4})
0.1 이렇게 커진다
5 ----------------------- defaultdict(<class 'int'>, {0.1: 5})
0.1 이렇게 커진다
6 ----------------------- defaultdict(<class 'int'>, {0.1: 6})
0.1 이렇게 커진다
7 ----------------------- defaultdict(<class 'int'>, {0.1: 7})
0.1 이렇게 커진다
8 ----------------------- defaultdict(<class 'int'>, {0.1: 8})
0.1 이렇게 커진다
9 ----------------------- defaultdict(<class 'int'>, {0.1: 9})
999 이렇게 커진다
1 ----------------------- defaultdict(<class 'int'>, {0.1: 9, 999: 1})
999 이렇게 커진다
2 ----------------------- defaultdict(<class 'int'>, {0.1: 9, 999: 2})
999 이렇게 커진다
3 ----------------------- defaultdict(<class 'int'>, {0.1: 9, 999: 3})
1 이렇게 커진다
1 ----------------------- defaultdict(<class 'int'>, {0.1: 9, 999: 3, 1: 1})
30 이렇게 커진다
1 ----------------------- defaultdict(<class 'int'>, {0.1: 9, 999: 3, 1: 1, 30: 1})
30 이렇게 커진다
2 ----------------------- defaultdict(<class 'int'>, {0.1: 9, 999: 3, 1: 1, 30: 2})
30 이렇게 커진다
3 ----------------------- defaultdict(<class 'int'>, {0.1: 9, 999: 3, 1: 1, 30: 3})
2번째 for문 0.1 9
check_list [[9, 0.1]]
2번째 for문 999 3
check_list [[9, 0.1], [3, 999]]
2번째 for문 1 1
check_list [[9, 0.1], [3, 999], [1, 1]]
2번째 for문 30 3
check_list [[9, 0.1], [3, 999], [1, 1], [3, 30]]
sort로 정렬 [[9, 0.1], [3, 999], [3, 30], [1, 1]]
[[9, 0.1], [3, 999], [3, 30], [1, 1]]입니다. [0.1]
[[9, 0.1], [3, 999], [3, 30], [1, 1]]입니다. [0.1, 999]
[[9, 0.1], [3, 999], [3, 30], [1, 1]]입니다. [0.1, 999, 30]
[0.1, 999, 30]