취미생활/CheckIO

[checkIO]Home 06.Sort Array by Element Frequency

우주먼지의하루 2020. 2. 13. 14:03
728x90

Sort the given iterable so that its elements end up in the decreasing frequency order, that is, the number of times they appear in elements. If two elements have the same frequency, they should end up in the same order as the first appearance in the iterable.

Input: Iterable

Output: Iterable

Example:

frequency_sort([4, 6, 2, 2, 6, 4, 4, 4]) == [4, 4, 4, 4, 6, 6, 2, 2]

frequency_sort(['bob', 'bob', 'carl', 'alex', 'bob']) == ['bob', 'bob', 'bob', 'carl', 'alex']

* 가장 많은 원소를 가진 것 대로 정렬해야한다.

* 빈도수가 같을때는 먼저 나온 것이 먼저 나오게 해야한다.

 

- 풀이

 

def frequency_sort(items):
    return sorted(items, key=lambda x:(-items.count(x),items.index(x)))
반응형