문제
nums
는 숫자로 이루어진 배열입니다.
가장 자주 등장한 숫자를 k
개수만큼 return 해주세요.
nums = [1,1,1,2,2,3],
k = 2
return [1,2]
nums = [1]
k = 1
return [1]
풀이
#1
from collections import Counter
def top_k(nums, k):
results = []
a = Counter(nums).most_common(k)
for i in a:
results.append(i[0])
return results
collection
모듈의 Counter
클래스
>>> from collections import Counter
>>> a = [1,8,9,7,8,8,4,7]
>>> Counter(a)
Counter({8: 3, 7: 2, 1: 1, 9: 1, 4: 1})
- 여러가지 methods (
c = Counter(a=4, b=2, c=0, d=-2)
)
-most_common(a)
: 가장 등장 개수가 많은 순서대로 a개의 key를 반환
-+c
: 0이나 음수의 counts 제거 > +c = Counter({'a': 4, 'b': 2})
-c.elements()
: c를 itertools.chain object
로 반환
> sorted(c.element) = ['a', 'a', 'a', 'a', 'b', 'b']